Home > other >  Query mongoose for every single element in array
Query mongoose for every single element in array

Time:06-12

I want to query mongoose for every single element in an array (which itself is also result of a query to mongoose) and append the result to each array element respected and return the array:


Service.find(query)
    .then((servicesList) => {
      const result = [];
      servicesList.forEach((service) => {
        Reviews.find({ service: service._id }).then((revs) => { 
          service.reviews = revs;                                      // Appending the result to element
          result.push(service);                                        // Pushing the element with it appended reviews to the result
        });
      });

      return res.json(result);
    })
    .catch((erro) => {
      return res.json({});
    });

but result won't get any value because return res.json(result);gets called before the Reviews.find() returns result

what is the way to solve the problem?

I have checked this : mongoose - Executing a query for each array element but it is not exactly what I want.

CodePudding user response:

res.json(result) is executed synchronously, before the individual asynchronous Reviews.find operations have finished. And this means before the array result has received any rows.

Use Promise.all to await all asynchronous operations before you return the result:

Promise.all(servicesList.map((service) =>
  Reviews.find({service: service._id}).then((revs) => { 
    service.reviews = revs;
    result.push(service);
  })
)).then(function() {
  res.json(result);
})

(Alternatively, consider using a join operation on the database to achieve all this with a single ServiceJoinReview.find operation.)

  • Related