当我在 MongoDB/Node/Express 中运行 collection.find()
时,我想在它完成时得到一个回调。正确的语法是什么?
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
参数,以便调用者知道查询是否有效。
2.x 驱动更新
find
现在返回光标而不是通过回调提供光标,因此典型用法可以简化为:
collection.find({'_id': o_id}).toArray(function(err, results) {...});
或者在这种需要单个文档的情况下,使用 findOne
会更简单:
collection.findOne({'_id': o_id}, function(err, result) {...});
Tôi là một lập trình viên xuất sắc, rất giỏi!