我是初學者,在meanstack開發中。我試圖在foreach循環中推入數組內的值,但最後我得到空數組。節點js Array.push()不能使用貓鼬
我的代碼:
router.get("/", function(req, res) {
ourpackage.find({}).sort({_id:1}).exec(function(err,resdoc){
var rest = [];
resdoc.forEach(function(doc){
masterRoomimage.find({ourpackageId:doc._id},function(err,ourpackageimagevalue){
if(err) res.send(err);
var ourpackagedetail = JSON.parse(JSON.stringify(doc));
var stringifyimages = JSON.parse(JSON.stringify(ourpackageimagevalue));
var ourpackage = _.merge({},ourpackagedetail,{masterRoomimages:stringifyimages});
rest.push(ourpackageimagevalue);
//print all rest array value
console.log(rest);
});
});
//print empty rest array value
console.log(rest);
res.send(rest);
});
});
ourpackage架構
{
"_id": "58e396d4215bc61338d2c06e",
"first_title": "test 1",
"berief_text": "<p>testing </p>",
}
ourpackagesimages架構
[
{
"_id": "59424d49fcc8100050916bf4",
"imageLocation": "first.jpg",
"ourpackageId": "58e396d4215bc61338d2c06e",
"__v": 0
},
{
"_id": "59424d49fcc8100050916bf5",
"imageLocation": "third.jpg",
"ourpackageId": "58e396d4215bc61338d2c077",
"__v": 0
},
{
"_id": "59490ad44e26c13324906433",
"imageLocation": "second.jpg",
"ourpackageId": "58e396d4215bc61338d2c06e",
"__v": 0
}
]
預期輸出
[
{
"_id": "58e396d4215bc61338d2c06e",
"first_title": "test 1",
"berief_text": "<p>testing </p>",
"ourpackagesimages": [
{
"_id": "59424d49fcc8100050916bf4",
"imageLocation": "first.jpg",
"ourpackageId": "58e396d4215bc61338d2c06e",
"__v": 0
},
{
"_id": "59490ad44e26c13324906433",
"imageLocation": "second.jpg",
"ourpackageId": "58e396d4215bc61338d2c06e",
"__v": 0
}
]
}
]
獲得的輸出空
[]
注意:'forEach'是同步的,而'find'是異步的。我認爲使用這個[answer](https://stackoverflow.com/a/41744323/1022914)中顯示的'aggregate'可能對你有用。 – Mikey