Swayam Shah
Swayam Shah

Reputation: 210

How to add data to mongoDB array?

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?

Upvotes: 0

Views: 89

Answers (2)

Hussein Mohamed
Hussein Mohamed

Reputation: 167

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

await restaurant.save()

Upvotes: 1

Mj Ebrahimzadeh
Mj Ebrahimzadeh

Reputation: 647

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} }

Upvotes: 1

Related Questions