数组为空时仍会在第一次渲染时呈现正确的数据,但在刷新后为空

时间:2017-11-29 08:23:19

标签: node.js mongodb mongoose

代码是

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服务器启动时,第一次正确呈现数据,但刷新后没有数据呈现。

1 个答案:

答案 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);
    });
}