【问题标题】:Mongoose does not send the updated result [duplicate]猫鼬不发送更新的结果[重复]
【发布时间】:2016-02-04 07:37:06
【问题描述】:

我正在尝试向数组中添加一个项目并取回更新后的模型。

我这样提出我的要求:

addCarToDriver(CarToAdd) {
 const self = this;
    request
       .put('api/drivers/' + this.state.race._id)
       .send({
        car: CarToAdd})
       .end(function(err, res) {
         console.log(res.body);
        self.setState({race: res.body});
       });
}

它在这里访问服务器:

MyRace.findByIdAndUpdate(
             req.params.myrace_id,
             { $push: { 'cars': req.body.car  } },
             function(er, model) {
             if (er) {
               console.log(err);
               return res.send(err);
              }
              console.log(model);
              return res.json(model);
            });

现在在请求回调中,我希望新的更新模型能够被记录,即使用新的Car。它不是。 “旧”版本被记录。但是,如果我刷新页面,模型就会更新为新车。

当然我需要直接在回调中设置状态。有关如何执行此操作的任何提示?

【问题讨论】:

    标签: javascript mongodb mongoose reactjs


    【解决方案1】:

    Mongoose 4 has changed.findAndUpdate 行为默认返回旧文档,如果你想要新的更新你需要通过{new:true}, because that was the actual behavior in MongoDB

    您可以修补查询以设置 options.new=true 以使用旧方法:

    var __setOptions = mongoose.Query.prototype.setOptions;
    mongoose.Query.prototype.setOptions = function(options, overwrite) {
      __setOptions.apply(this, arguments);
      this.options['new'] = true;
      return this;
    };
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 2017-10-03
      • 2015-08-04
      • 1970-01-01
      • 2019-07-26
      • 2019-08-07
      • 2020-11-13
      • 2014-05-30
      相关资源
      最近更新 更多