简体   繁体   English

如何在 MongoDB collection.find() 上获得回调

[英]How to get a callback on MongoDB collection.find()

When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished.当我在 MongoDB/Node/Express 中运行collection.find()时,我想在它完成后得到一个回调。 What's the correct syntax for this?什么是正确的语法?

 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
  }

That's the correct callback syntax, but what find provides to the callback is a Cursor , not an array of documents.这是正确的回调语法,但find提供给回调的是Cursor ,而不是文档数组。 So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:因此,如果您希望回调以文档数组的形式提供结果,请在游标上调用toArray以返回它们:

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

Note that your function's callback still needs to provide an err parameter so that the caller knows whether the query worked or not.请注意,您的函数的回调仍然需要提供一个err参数,以便调用者知道查询是否有效。

2.x Driver Update 2.x 驱动程序更新

find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to: find现在返回游标而不是通过回调提供它,因此典型用法可以简化为:

collection.find({'_id': o_id}).toArray(function(err, results) {...});

Or in this case where a single document is expected, it's simpler to use findOne :或者在需要单个文档的情况下,使用findOne更简单:

collection.findOne({'_id': o_id}, function(err, result) {...});

Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked.根据 JohnnyHK 的回答,我只是将我的调用包装在 db.open() 方法中并且它起作用了。 Thanks @JohnnyHK.谢谢@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);
             });
         });
     });
});

Hope it is helpful as an example.希望它作为一个例子有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM