【问题标题】:Mongoose .save() only runs 5 timesMongoose .save() 只运行 5 次
【发布时间】:2021-08-25 04:10:58
【问题描述】:

我有一个代码通过我的 House 数据播种器与月份的关系进行映射,发生的奇怪事情是它循环到最后,但在月份模型中只保存 5 条记录

    const insertMonths = houses.map((house, i) => {
      const months = new Month({ year: "2021" });
      months.save();
      console.log(i);
      return { ...house, months: months._id };
    });
    await House.insertMany(insertMonths);

我不知道是什么导致了这种行为。

【问题讨论】:

  • 你有没有考虑过months.save()是异步的,需要让map函数异步?
  • 是的,但是如果我使用异步等待,它似乎无法获取每个房屋的数据
  • 我已经让它运行了,但它似乎运行了,但最后它出错了由于某种原因它给了我一个验证错误,我在 map 函数上使用了 promise.all `const insertMonths = await Promise.all(houses.map(async (house) => { const 月 = new Month({ year: "2021" }); const finalHouses = { ...house, 月:months._id }; 控制台.log(finalHouses); 返回 { finalHouses }; }) );等待 House.insertMany(insertMonths); `
  • 检查一下,如果有帮助的话。 stackoverflow.com/questions/46457071/…
  • 我使用 Promise 解决了它。我现在就发布答案

标签: javascript mongodb express mongoose


【解决方案1】:

我使用了 Promise.all 函数

    const insertMonths = await Promise.all(
      houses.map(async (house) => {
        const createdHouse = await House.create(house);
        const createdMonth = await Month.create({ year: "2021" });
        const updateHouse = await House.findById(createdHouse);
        updateHouse.yearlyDues.push(createdMonth._id);
        await updateHouse.save();
        const updateMonth = await Month.findById(createdMonth);
        updateMonth.house = createdHouse._id;
        await updateMonth.save();
      })
    );    const insertMonths = await Promise.all(
      houses.map(async (house) => {
        const createdHouse = await House.create(house);
        const createdMonth = await Month.create({ year: "2021" });
        const updateHouse = await House.findById(createdHouse);
        updateHouse.yearlyDues.push(createdMonth._id);
        await updateHouse.save();
        const updateMonth = await Month.findById(createdMonth);
        updateMonth.house = createdHouse._id;
        await updateMonth.save();
      })
    );

我真的不知道它是如何完全工作的,但它可以让你进入 Promise 并查明值或其他内容,如果我错了,请编辑。

【讨论】:

    猜你喜欢
    • 2020-07-02
    • 2017-09-30
    • 1970-01-01
    • 2021-12-30
    • 2019-10-30
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多