0

I am attempting to edit an array within an object on my Express/NodeJS application. Below is the data from the collection of Locations:

{ _id"56873fc9182b3741059357d0", 
  longitude: 113.83507800000007, 
  latitude: 22.1533884, 
  location: "Hong Kong", 
  name"Hong Kong", 
  __v0, 
 reviews: {review_id: "OBY3iC1IcdIE", comment: null, rating: null }
          {review_id: "3433iC1IcdIY", comment: null, rating: null }
} 

I'd like to edit one of the reviews (example: review_id:"OBY3iC1IcdIE") but my server side code makes the app crash. My current server side code is:

 exports.editReview = function(req, res) { 
    Location.update({ _id: req.params.location_id, reviews.review_id: req.params.review_id }, 
  { $set: { review.comment: req.body.comment, 
 review.rating: req.body.rating }}, function(err, location) { 
      if(err)    
         res.send(err);  
      res.json(location); 
  }); 
 }; 
1
  • { $set: {" reviews.comment": req.body.comment, "review.rating": req.body.rating }}. When ever you need nested fields you need to use double quotes Commented Jan 4, 2016 at 6:03

2 Answers 2

2
 exports.editReview = function(req, res) { 
    Location.update({ _id: req.params.location_id, "reviews.review_id": req.params.review_id }, 
  { $set: { "reviews.comment": req.body.comment, 
 "reviews.rating": req.body.rating }}, function(err, location) { 
      if(err)    
         res.send(err);  
      res.json(location); 
  }); 
 };

Try this, add double quotes when you need to use nested fields. I am assuming your mongodb setup is fine in your app

Sign up to request clarification or add additional context in comments.

2 Comments

I just added this code and got a Mongo Error with the message "cannot use the part (reviews of reviews.comment) to traverse the element."
I just fixed the code and it works. With your help, I added $ signs to "reviews.$.comment" and "reviews.$.rating" as per the MongoDb documentation.
0

I have to say thank you @SumanLama for the assistance. I added the necessary $ signs as per the MongoDB documentation.

exports.editReview = function(req, res) { 
  Location.update({ _id: req.params.location_id, "reviews.review_id": req.params.review_id }, 
    { $set: { "reviews.$.comment": req.body.comment, 
       "reviews.$.rating": req.body.rating }}, function(err, location) { 
        if(err)    
          res.send(err);  
        res.json(location); 
 }); 
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.