Node.js NodeJS阵列推送不工作
我正在执行非常简单的请求,从MongoDB获取一些数据,然后将它们发送到我的视图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 = []
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 });
}
});
});
});
});
更好的方法是使用承诺,但这不是必需的。如果您可以在回答问题时突出显示或描述找到解决方案所需的更改,这将非常方便