[英]How to get a callback on MongoDB collection.find()
当我在 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) {...});
根据 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);
});
});
});
});
希望它作为一个例子有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.