【问题标题】:update nested schema express更新嵌套模式表达
【发布时间】:2014-07-13 20:13:45
【问题描述】:

我想在 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: []
  }

});

谁能帮帮我?

【问题讨论】:

    标签: rest express mongoose put


    【解决方案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 };
                        }
    

    【讨论】:

      【解决方案2】:

      如果您希望 Mongoose 为您跟踪更改,您需要告诉 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');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-16
        • 1970-01-01
        • 2014-07-13
        相关资源
        最近更新 更多