I read another post about this issue, but I was unable to figure out how to apply it to my situation (node js Array.push() not working using mongoose)
This is my Mongoose async populate function, what I want to do is push a value to a final array which includes each review which I will later do something with. However .push() does not work and I always get an empty array; From what I have read it has to do with the for loop being synchronous and not being able to accept async values but im unsure on what to do to fix it
//Empty array will be populated with all scores
const allReviewsRating = []
this.populate("reviews").then(async function (allReviews) {
for (const review of allReviews.reviews) {
allReviewsRating.push(review.rating)
}
// async.map(review, allReviews.reviews)
})
But even when I do something like this
const allReviewsRating = []
this.populate("reviews").then(async function (allReviews) {
allReviewsRating.push(`1`)
for (const review of allReviews.reviews) {
allReviewsRating.push(review.rating)
}
// async.map(review, allReviews.reviews)
})
The final array is empty which confuses me even more
I was wondering what I need to do in order to get my array to not be empty, and actually have the values I want it to have
2
Answers
I think you need to check,
this.populate()
function that is not populatingreviews
and if it’s populating then the issue is in thisallReviews.reviews
reviews are not in allReviews. Everything else is working. I tested it on my system.Try
.lean()
in your query or doJSON.parse(JSON.stringify(allReviews))
then push data in array.