NodeJS / MongoDB更新对象中的数组

时间:2016-01-04 05:09:31

标签: node.js mongodb express updates

我正在尝试编辑Express / NodeJS应用程序中对象内的数组。以下是地点集合中的数据:

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

我想编辑其中一条评论(例如:review_id:“OBY3iC1IcdIE”),但我的服务器端代码会导致应用崩溃。我当前的服务器端代码是:

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

2 个答案:

答案 0 :(得分: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); 
  }); 
 };

尝试此操作,在需要使用嵌套字段时添加双引号。我假设您的应用程序中的mongodb设置正常

答案 1 :(得分:0)

我要感谢@SumanLama的帮助。我根据MongoDB文档添加了必要的$符号。

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