更新嵌套模式表达

时间:2014-05-24 15:21:15

标签: rest express mongoose put

当我想在express中更新我的嵌套对象时,我遇到了问题。这是我的代码:

.put(function(req, res) {
            Place.findById(req.params.place_id, function(err, place) {

                    if (err)
                            res.send(err);
                    if (typeof req.body.zip !== 'undefined') {
                            place.zip = req.body.zip;     
                    }
                    if (typeof req.body.loc !== 'undefined') {
                            place.loc = req.body.loc;
                    }
                    if (typeof req.body.coordinates !== 'undefined') {
                            place.coordinates = req.body.coordinates;
                    }

                    place.save(function(err) {
                            if (err)
                                    res.send(err);

                            res.json({ message: 'Place updated!' });
                    });

            });

    });

它正在工作,当我想更新zip时,但我无法修改坐标。我也试过了place.loc.coordinates。我正在使用curl来更新,也许那个命令是错误的。我试过了

curl -X PUT -d loc.coordinates=[1.3,3.2] 'http://localhost:8080/api/places/A38'
curl -X PUT -d coordinates=[1.3,3.2] 'http://localhost:8080/api/places/A38'

命令。

我的架构是:

var placeSchema = new Schema({
   _id:  String,
  zip: Number,
    loc: {
      type: { type: String }
    , coordinates: []
  }

});

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

我尝试了你的两个想法,但不幸的是那些没有用过。 我找到了一个解决方案,也许它不优雅,但有效: 我将模式更改为:

var placeSchema = new Schema({
  _id:  String,
  zip: Number,
  loc: {
    type: Object
  ,   index: '2dsphere'
  }
});

我的新代码是:

if (typeof req.body.coordinates !== 'undefined') {
                            place.loc = { type: 'Point', coordinates: req.body.coordinates };
                    }

答案 1 :(得分:0)

如果您希望它跟踪您的更改,您需要告诉Mongoose coordinates数组包含的内容。因此,将架构定义更改为:

var placeSchema = new Schema({
   _id:  String,
  zip: Number,
  loc: {
    type: { type: String },
    coordinates: [Number]
  }
});

另一种方法是明确将coordinates标记为已更改:

place.coordinates = req.body.coordinates;
place.markModified('coordinates');
相关问题