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

别说谁变了你拦得住时间么 提交于 2020-01-18 07:15:34

问题


When I run collection.find() in MongoDB/Node/Express, I'd like to get a callback when it's finished. 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
  }

回答1:


That's the correct callback syntax, but what find provides to the callback is a Cursor, not an array of documents. So if you want your callback to provide results as an array of documents, call toArray on the cursor to return them:

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.

2.x Driver Update

find now returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:

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:

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



回答2:


Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @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.



来源:https://stackoverflow.com/questions/11661545/how-to-get-a-callback-on-mongodb-collection-find

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!