问题描述
我有一条复杂的路线,我想用猫鼬修改我从数据库中获得的信息 当它结束我的项目的对象数组时,每个对象包含另一个集合女巫的ID数组,我必须为每个对象添加一个新属性, 代码如下:
/* here i am trying to get the list of items */
let itemsList = await Items.find().lean();
/* Now i want to loop through them to go to each ones inner array of IDs */
itemsList.forEach(item => {
/* here i am making a new object property to containg what the IDs pointing at */
item.theProducts = [];
/* Now i am going through the array of IDs */
item.IDsArray.forEach(async product => {
/* finding each product by the ID */
let foundProduct = await SlemaniMaxzan.findById(product,{ _id: 0,productName: 1,productPrice: 1 }).lean();
/* showing the product */
console.log(foundProduct);
/* Now i am pushing it to the new property */
item.theProducts.push(foundProduct);
});
});
/* trying to check it the values has been added */
/* i expect the values has been added jsut fine,but it is not working */
console.log(itemsList);
res.render("mandubakan",{ title: "list",mandubakan: itemsList });
当我运行它时,它没有被添加,它只是为项目创建了一个新的空数组,但没有添加任何内容,并且程序甚至在记录每个foundProduct之前都记录了itemsList
解决方法
对于异步函数,必须避免使用方法forEach
。
尝试类似的事情:
let itemsList = await Items.find().lean();
for (let item of itemsList) {
item.theProducts = [];
for (let product of item.IDsArray) {
let foundProduct = await SlemaniMaxzan.findById(product,{
_id: 0,productName: 1,productPrice: 1,}).lean();
console.log(foundProduct);
item.theProducts.push(foundProduct);
}
}
console.log(itemsList);
res.render("mandubakan",{ title: "list",mandubakan: itemsList });