【问题标题】:Mongoose: how to check if document is modified via model.findOneAndUpdate()Mongoose:如何通过 model.findOneAndUpdate() 检查文档是否被修改
【发布时间】:2016-05-05 17:11:06
【问题描述】:

在猫鼬中,我们可以使用model.update()检查更新操作是否修改了文档:

model.update(query, update, function(err, raw){
    if (raw.nModified >= 1) console.log('document is modified!')
});

有没有办法对model.findOneAndUpdate() 做同样的事情?

model.findOneAndUpdate(query, update, { new: true }, function(err, doc){
    if (doc) {
        // So MongoDB found the document, but is there a way 
        // to know the document was indeed modified?
    }
});

【问题讨论】:

标签: node.js mongodb mongoose database


【解决方案1】:

您可以将选项 { passRawResult : true } 传递给 mongoose,以建议 mongoose 将底层 mongodb 驱动程序(在本例中为 mongodb-native)的原始结果作为回调的第三个参数传递。

findOneAndUpdate 的 mongodb 原生文档

model.findOneAndUpdate(query, update, { new: true, passRawResult : true }, function(err, doc, res){
    // res will look like
    // { value: { _id: 56a9fc80a7f9a4d41c344852, name: 'hugo updated', __v: 0 },
    //   lastErrorObject: { updatedExisting: true, n: 1 },
    //   ok: 1 }
});

如果由于找不到匹配的文档而导致更新失败,null res 将被传递给回调。如果文档匹配但字段值与更新 res 对象之前相同,则无法为您提供足够的信息来确定匹配文档的值是否已更新。

【讨论】:

  • 这是部分正确的,因为它至少会报告某些内容是否有效匹配。但是,如果您发送完全相同的更新(或任何其他尝试将字段设置为其已有值的内容),那么即使没有实际更改,这仍会将文档报告为“已更新”。这是因为此方法仍在使用旧版 API,并且在引入 Bulk API(现代 API 实现使用)之前,没有准确报告这是否是修改。但值得称赞的是,提到了未记录的选项。
猜你喜欢
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-05
  • 2013-12-16
  • 2014-04-29
  • 1970-01-01
相关资源
最近更新 更多