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
}
That’s the correct callback syntax, but what
findprovides to the callback is aCursor, not an array of documents. So if you want your callback to provide results as an array of documents, calltoArrayon the cursor to return them:Note that your function’s callback still needs to provide an
errparameter so that the caller knows whether the query worked or not.2.x Driver Update
findnow returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:Or in this case where a single document is expected, it’s simpler to use
findOne: