I read another post about this problem but I can't figure out how to apply it to my situation (node js Array.push() not working when using mongoose)
This is my Mongoose async populate function, what I want to do is push a value into a final array containing each comment, which I will do something with later. However, .push() doesn't work, I always get an empty array; from what I've read, this has to do with the for loop being synchronous and not being able to accept asynchronous values, but I'm not sure how to fix it
//空数组将被填充所有分数 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 if 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 want to know what I need to do so that my array is not empty and actually has the values I want
I think you need to check,
this.populate()
function is not populatingreviews
, if it is, then the problem may beallReviews.reviews
, that is, there are no comments among all comments. All other functions are normal. I tested it on my system.