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.