如何获取MongoDB collection.find()的回调 [英] How to get a callback on MongoDB collection.find()
问题描述
当我在MongoDB / Node / Express中运行 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
}
推荐答案
这是正确的回调语法,但是什么 find
提供给回调是一个 光标
,而不是一系列文档。所以如果你希望你的回调作为文件数组提供结果,请调用 toArray
返回:
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();
});
请注意,您的函数的回调仍然需要提供一个 err
参数,以便调用者知道查询是否工作。
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驱动程序更新
find
现在返回光标,而不是通过回调提供它,所以典型的用法可以简化为:
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) {...});
或者在这种情况下,单个文档是预期的,使用 findOne
:
Or in this case where a single document is expected, it's simpler to use findOne
:
collection.findOne({'_id': o_id}, function(err, result) {...});
这篇关于如何获取MongoDB collection.find()的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!