Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS阵列推送不工作_Node.js_Mongodb - Fatal编程技术网

Node.js NodeJS阵列推送不工作

Node.js NodeJS阵列推送不工作,node.js,mongodb,Node.js,Mongodb,我正在执行非常简单的请求,从MongoDB获取一些数据,然后将它们发送到我的视图 router.get('/', isAuthenticated, function(req, res) { Conversation.findAllConversation(req.user._id, function(err, data) { if (err) return console.error(err); // handle this var array = []

我正在执行非常简单的请求,从MongoDB获取一些数据,然后将它们发送到我的视图

router.get('/', isAuthenticated, function(req, res) {
    Conversation.findAllConversation(req.user._id, function(err, data) {
        if (err) return console.error(err); // handle this

        var array = [];

        data.forEach(function (element, index, array){
            ConversationReply.findLastReply(element._id, function(err, replys) {
                if(err) return cosole.log(err);
                console.log(replys);
                array.push(replys);
            });
        });

        console.log(array);

        res.render('messages/index', {
          title : 'Messages', 
          conversations: data,
          user: req.user, 
          lastReplys: array });
   });
});

但所有来自reply的数据并不是推送到我的数组,而是发送空数据。Console.log(reply)正确显示我的所有回复。

findLastReply异步返回,而请求函数同步进行。要解决此问题,我将执行以下操作:

router.get('/', isAuthenticated, function(req, res) {
    Conversation.findAllConversation(req.user._id, function(err, data) {
        if (err) return console.error(err); // handle this

        var array = [];

        data.forEach(function (element, index, array){
            ConversationReply.findLastReply(element._id, function(err, replys) {
                if(err) return cosole.log(err);
                console.log(replys);
                array.push(replys);

                if (array.length === data.length) {
                  // we are done! :D
                  console.log(array);

                  res.render('messages/index', {
                    title : 'Messages', 
                    conversations: data,
                    user: req.user, 
                    lastReplys: array });
                }
            });
        });
   });
});

更好的方法是使用承诺,但这不是必需的。

如果您可以在回答问题时突出显示或描述找到解决方案所需的更改,这将非常方便