node.js 如何在 MongoDB collection.find() 上获得回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11661545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a callback on MongoDB collection.find()
提问by John
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?
当我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
}
采纳答案by JohnnyHK
That's the correct callback syntax, but what findprovides 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 toArrayon the cursor to return them:
这是正确的回调语法,但find提供给回调的是一个Cursor,而不是文档数组。因此,如果您希望回调以文档数组的形式提供结果,请调用toArray游标以返回它们:
collection.find({'_id':o_id}, function(err, cursor){
cursor.toArray(callback);
db.close();
});
Note that your function's callback still needs to provide an errparameter so that the caller knows whether the query worked or not.
请注意,您的函数的回调仍然需要提供一个err参数,以便调用者知道查询是否有效。
2.x Driver Update
2.x 驱动程序更新
findnow returns the cursor rather than providing it via a callback, so the typical usage can be simplified to:
find现在返回游标而不是通过回调提供它,因此典型用法可以简化为:
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:
或者在需要单个文档的情况下,使用更简单findOne:
collection.findOne({'_id': o_id}, function(err, result) {...});
回答by Anmol Saraf
Based on JohnnyHK answer I simply wrapped my calls inside db.open() method and it worked. Thanks @JohnnyHK.
根据 JohnnyHK 的回答,我只是将我的调用包装在 db.open() 方法中并且它起作用了。谢谢@JohnnyHK。
app.get('/answers', function (req, res){
db.open(function(err,db){ // <------everything wrapped inside this function
db.collection('answer', function(err, collection) {
collection.find().toArray(function(err, items) {
console.log(items);
res.send(items);
});
});
});
});
Hope it is helpful as an example.
希望它作为一个例子有帮助。

