如何在MongoDB collection.find()上获取回调
当我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
}
回答:
这是正确的回调语法,但是find提供给回调的是一个Cursor,而不是文档数组。因此,如果您希望回调将结果作为文档数组提供,请调用toArray游标以将其返回:
collection.find({'_id':o_id}, function(err, cursor){ cursor.toArray(callback);
db.close();
});
请注意,函数的回调仍需要提供一个err参数,以便调用者知道查询是否有效。
find 现在返回游标而不是通过回调提供游标,因此典型用法可以简化为:
collection.find({'_id': o_id}).toArray(function(err, results) {...});或者在这种情况下,期望使用单个文档,则使用起来更简单findOne:
collection.findOne({'_id': o_id}, function(err, result) {...});以上是 如何在MongoDB collection.find()上获取回调 的全部内容, 来源链接: utcz.com/qa/417903.html

