【问题标题】:mongoose Model.update() - only update provided valuesmongoose Model.update() - 只更新提供的值
【发布时间】:2017-03-20 20:44:15
【问题描述】:

我有以下架构:

const wordSchema = mongoose.Schema({
  author: {type: String, index: true, default: 'unknown'},
  quote: String,
  source: {type: String, default: 'unknown', index: true},
  rating: {type: Number, default: 0},
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now},
});

我的快递应用程序中的以下 PUT 路线:

// Route to update a quote in the DB
app.put('/words/:id', function(req, res) {
  const quote = new Word({
    _id: req.params.id,
    author: req.body.author,
    quote: req.body.quote,
    source: req.body.source,
    rating: req.body.rating,
    updatedAt: Date.now(),
  });
  Word.update(quote, function(err, raw) {
    if (err) {
      res.send(err);
    }
    res.send(raw);
  });
});

现在,当我发送 PUT 请求时,如果未提供使用默认值设置的参数,它们将使用 Schema 中的默认值填充。如何仅更新提供的值?

感谢您的帮助。

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    不要为更新创建新的 Word 实例,update 采用条件和 doc 对象参数,让您可以单独标识要更新的文档并提供其更新后的值:

    app.put('/words/:id', function(req, res) {
      const doc = {
        author: req.body.author,
        quote: req.body.quote,
        source: req.body.source,
        rating: req.body.rating,
        updatedAt: Date.now(),
      });
      Word.update({_id: req.params.id}, doc, function(err, raw) {
        if (err) {
          res.send(err);
        }
        res.send(raw);
      });
    });
    

    【讨论】:

    【解决方案2】:

    您可以尝试使用 Model.findByIdAndUpdate() 方法,其中所有不是原子操作名称的顶级更新键都被视为设置操作,并且从不执​​行默认值/设置器。您可以使用 lodash 的 _.assign() 方法来设置 updatedAt 字段:

    // Route to update a quote in the DB
    app.put('/words/:id', function(req, res) {
        const update = _.assign({ "updatedAt": new Date() }, req.body);
        Word.findByIdAndUpdate(req.params.id, update, function(err, raw) {
            if (err) {
                res.send(err);
            }
            res.send(raw);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2016-11-27
      相关资源
      最近更新 更多