Home > Software engineering >  How to add data to mongoDB array?
How to add data to mongoDB array?

Time:10-23

Below is my code to add reviews to my reviews array in the restaurant object

async created (restaurantId, title, reviewer, rating, dateOfReview, review) {
    
    const restaurantsCollection = await restaurants();
    let newReview = {
      restaurantId : restaurantId,
      title : title,
      reviewer : reviewer,
      rating : rating,
      dateOfReview : dateOfReview,
      review : review
    };

    const restaurant = await restaurantsCollection.findOne({ _id: restaurantId });
    restaurant.reviews.push(newReview);

}

This does not add any data to the DB, what is the right way to do this?

CodePudding user response:

If I have understand right, you need to call the update after pushing that to your reviews.

await restaurantsCollection.updateOne({restaurantId : newReview.restaurantId},{ $set: {reviews: restaurant.reviews} }

or you can easily push it like this and no need to do the findOne query:

 await restaurantsCollection.updateOne({restaurantId : newReview.restaurantId},{ $push: {reviews: newReview.review} }

CodePudding user response:

Don't forget to save the review after pushing it to the array.

await restaurant.save()
  • Related