[英]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.