代码是
router.get('/', function(req, res, next){
var successMsg = req.flash('success')[0];
Section.findOne({'sectionId': 'K111'}, function(err, doc){
var result = [];
studentsList = doc.studentsList;
studentsList.forEach(function(ele){
Student.findById(ele, function(errs, docs){
result.push(docs);
});
});
console.log(result);
res.render('shop/index', {students: result, successMsg: successMsg, noMessages: !successMsg});
});
});
这里我使用mongoose从MongoDb中检索数据。 即使在findById()之后推送文档,结果数组也是空的。当nodejs服务器启动时,第一次正确呈现数据,但刷新后没有数据呈现。
答案 0 :(得分:1)
你必须学习承诺或者你可以使用递归:
router.get('/', function(req, res, next) {
var successMsg = req.flash('success')[0];
Section.findOne({'sectionId': 'K111'}, function(err, doc){
var result = [];
studentsList = doc.studentsList;
function onDone () {
console.log(result);
res.render('shop/index', {
students: result,
successMsg: successMsg,
noMessages: !successMsg
});
}
function findNext(i) {
if (i == studentsList.length)
return onDone();
var ele = studentsList[i];
Student.findById(ele, function(err, docs) {
if (err)
return next(err); // Break and go to error handler
result.push(docs);
findNext(i + 1);
});
}
findNext(0);
});
}