如何在MongoDB上收集回调.find()

Joh*_*ohn 44 mongodb node.js express

当我collection.find()在MongoDB/Node/Express中运行时,我想在它完成后得到一个回调.这个的正确语法是什么?

 function (id,callback) {

    var o_id = new BSON.ObjectID(id);

    db.open(function(err,db){
      db.collection('users',function(err,collection){
        collection.find({'_id':o_id},function(err,results){  //What's the correct callback synatax here?
          db.close();
          callback(results);
        }) //find
      }) //collection
    }); //open
  }
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 41

这是正确的回调语法,但find为回调提供的是一个文件Cursor,而不是一个文档数组.因此,如果您希望回调将结果作为文档数组提供,请调用toArray游标返回它们:

collection.find({'_id':o_id}, function(err, cursor){
    cursor.toArray(callback);
    db.close();
});
Run Code Online (Sandbox Code Playgroud)

请注意,函数的回调仍然需要提供一个err参数,以便调用者知道查询是否有效.

2.x驱动程序更新

find 现在返回游标而不是通过回调提供它,因此典型用法可以简化为:

collection.find({'_id': o_id}).toArray(function(err, results) {...});
Run Code Online (Sandbox Code Playgroud)

或者在预期单个文档的情况下,使用起来更简单findOne:

collection.findOne({'_id': o_id}, function(err, result) {...});
Run Code Online (Sandbox Code Playgroud)

  • 在这种情况下,您需要使用`findOne`,它直接将文档提供给回调.见http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#findone (2认同)

Anm*_*raf 21

根据JohnnyHK的回答,我只是将我的调用包装在db.open()方法中,并且它有效.谢谢@JohnnyHK.

app.get('/answers', function (req, res){
     db.open(function(err,db){ // <------everything wrapped inside this function
         db.collection('answer', function(err, collection) {
             collection.find().toArray(function(err, items) {
                 console.log(items);
                 res.send(items);
             });
         });
     });
});
Run Code Online (Sandbox Code Playgroud)

希望它有用作为一个例子.

  • *他们称之为......回调地狱!它始于...* (13认同)