0

I am trying to query second table from the response of first table. Since I have to update data for each of the record , I am calling mongoDB query inside loop.

here res is the response of first table, problem is in this line:

const secondRes = await myModel.paginate({name:doc.name});

await is not allowed since loop is synchronous and if I am removing await from this line, it is not giving result even if data is present in DB. if I am moving out db call from loop and directly pasting in getResponse function, I am getting response from database but I need to call within loop, please anyone suggest , how can I solve this.

Thanks in advance.

exports.getResponse = async (req,res)=>{
   res.docs.forEach(doc => {
       let response1 = {};
       const secondRes = await myModel.paginate({name:doc.name});
       console.log("SecondRes ::"+JSON.stringify(secondRes));
   }
}
tiya
  • 117
  • 1
  • 3
  • 14
  • for loop instead of foreach? https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – cmgchess Apr 14 '23 at 04:26

1 Answers1

1

forEach does not work in this case, I would suggest starting parallel queries to reduce API latency.

const getResponse = async (req,res)=> {
  const queries = res.docs.map(doc => myModel.paginate({name:doc.name}));
  const secondRes = await Promise.allSettled(queries);

  // In case you want to filter
  // const errors = secondRes.filter(res => res.status === 'rejected'); 
  // const success = secondRes.filter(res => res.status === 'fulfilled');

  console.log("Result ::", JSON.stringify(secondRes));
}
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37