skip to Main Content

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


  1. I think you need to check, this.populate() function that is not populating reviews and if it’s populating then the issue is in this allReviews.reviews reviews are not in allReviews. Everything else is working. I tested it on my system.

    Login or Signup to reply.
  2. Try .lean() in your query or do JSON.parse(JSON.stringify(allReviews)) then push data in array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search