我想让我的路线等待所有要使用nodeJS完成的过程

问题描述

我有一条复杂的路线,我想用猫鼬修改我从数据库中获得的信息 当它结束我的项目的对象数组时,每个对象包含另一个集合女巫的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 });


相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...