0

I have a code that maps through my House data seeder with a relation of month, weird thing that happens is it loops through the end but only saves 5 records in the month model

    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);

I don't know what causes this behavior.

kgcusi
  • 215
  • 7
  • 18
  • have you considered that months.save() is async and you need to make the map function async? – arianpress Jun 08 '21 at 06:53
  • Yes, but it errors me out that it can't seem to get the data of each individual house if I use async await – kgcusi Jun 08 '21 at 06:58
  • I've got it to run but it seems that it runs, but it errors out at the end it gives me a validation error for some reason, I used promise.all on the map function ` const insertMonths = await Promise.all( houses.map(async (house) => { const months = new Month({ year: "2021" }); const finalHouses = { ...house, months: months._id }; console.log(finalHouses); return { finalHouses }; }) ); await House.insertMany(insertMonths); ` – kgcusi Jun 08 '21 at 07:36
  • check this, if it helps. https://stackoverflow.com/questions/46457071/using-mongoose-promises-with-async-await – Shraddha Yadav Jun 09 '21 at 05:44
  • I solved it using Promise.all I'll post the answer now – kgcusi Jun 09 '21 at 05:48

1 Answers1

0

I used the Promise.all function

    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();
      })
    );

I don't really know how to it fully works but it lets you get inside the Promise and pinpoint the values or something, edit if I'm wrong.

kgcusi
  • 215
  • 7
  • 18