Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

node.js - 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. 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
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) {...});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...