Node.js,Mongo查找并返回数据

VB6和MySql 15年后,我对node和mongo是新手。 我确定这不是我最终的程序将会使用的,但是我需要对如何在另一个模块中调用函数并获得结果有一个基本的了解。

我想要一个模块有一个function打开一个数据库,find一个集合,并返回结果。 我可能还想为其他集合在该模块中添加更多的function。 现在我需要它尽可能简单,我可以添加error handling程序,等等。 我一直在尝试不同的方法,module.exports = {…围绕函数和出它,.send,返回所有没有运气。 我知道这是asynchronous的,所以程序可能已经通过显示点,然后数据就在那里。

下面是Mongo用col1集合运行db1的一个数据库的例子。

Db1.js var MongoClient = require('mongodb').MongoClient; module.exports = { FindinCol1 : function funk1(req, res) { MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) { if (err) { return console.dir(err); } var collection = db.collection('col1'); collection.find().toArray(function (err, items) { console.log(items); // res.send(items); } ); }); } }; app.js a=require('./db1'); b=a.FindinCol1(); console.log(b); 

Console.log(项目)工作时,“FindinCol1”调用,但不是console.log(b)(返回'未定义'),所以我没有得到的回报,或者我粘贴它的时间是返回。 我已经阅读了数十篇文章,并观看了数十个video,但我仍然坚持在这一点上。 任何帮助将不胜感激。

正如在另一个答案中提到的,这段代码是asynchronous的,你不能简单的沿着callback链(嵌套函数)返回你想要的值。 您需要公开一些接口,让您在获得所需的值(因此,调用callback或callback)时发出调用代码的信号。

在另一个答案中提供了一个callback示例,但是有一个绝对值得探索的选项: promises 。

你可以用一个callback函数来调用所需的结果,而不是callback函数返回一个可以input两个状态,履行或拒绝的承诺。 调用代码等待承诺进入这两个状态中的一个,当它调用时调用适当的函数。 模块通过resolvereject触发状态变化。 无论如何,这里是一个使用承诺的例子:

Db1.js:

 // db1.js var MongoClient = require('mongodb').MongoClient; /* node.js has native support for promises in recent versions. If you are using an older version there are several libraries available: bluebird, rsvp, Q. I'll use rsvp here as I'm familiar with it. */ var Promise = require('rsvp').Promise; module.exports = { FindinCol1: function() { return new Promise(function(resolve, reject) { MongoClient.connect('mongodb://localhost:27017/db1', function(err, db) { if (err) { reject(err); } else { resolve(db); } } }).then(function(db) { return new Promise(function(resolve, reject) { var collection = db.collection('col1'); collection.find().toArray(function(err, items) { if (err) { reject(err); } else { console.log(items); resolve(items); } }); }); }); } }; // app.js var db = require('./db1'); db.FindinCol1().then(function(items) { console.info('The promise was fulfilled with items!', items); }, function(err) { console.error('The promise was rejected', err, err.stack); }); 

是的,这是一个asynchronous代码,并return您将得到的MongoClient对象或什么都没有,根据您的位置。

你应该使用一个callback参数:

 module.exports = { FindinCol1 : function funk1(callback) { MongoClient.connect("mongodb://localhost:27017/db1", function (err,db) { if (err) { return console.dir(err); } var collection = db.collection('col1'); collection.find().toArray(function (err, items) { console.log(items); return callback(items); }); }); } }; 

将一个callback函数传递给FindinCol1

 a.FindinCol1(function(items) { console.log(items); }); 

我build议你检查这篇文章: https : //docs.nodejitsu.com/articles/getting-started/control-flow/what-are-callbacks