0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.