【发布时间】:2015-06-15 23:28:27
【问题描述】:
我遇到需要从 nodejs(expressjs) 代码触发 mongodb 查询并将查询结果作为对我的 web api 请求的响应传递的情况,但在我的查询执行下一行代码之前执行并返回空白响应。我写的代码如下,
router.get('/recent', function (req, res){
var result = [];
router.db.collection('Posts').find({},{ _id : 1, uid : 1, imagePath : 1, cntLikes : 1, uploadDate : 1}).limit(5).sort({ uploadDate : -1 }).toArray(function(err, docs) {
docs.forEach( function (doc){
router.db.collection('Users').findOne({ "_id" : mongodb.ObjectId(doc.uid)}, function (err, user){
doc.username = user;
result.push(doc);
});
});
res.send(result); // this line send empty result to caller
});
});
我尝试了回调方法 async.waterfall 并以编程方式停止执行,但一切都失败了。我也尝试过承诺,但我认为承诺在这种情况下对我没有帮助。
【问题讨论】:
标签: node.js mongodb asynchronous callback