代码是
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服务器启动时,数据是第一次正确渲染的数据,但是刷新后没有渲染数据。
您必须学习承诺,或者可以使用递归:
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);
});
}