【问题标题】:how to check if the document updated was really modified?如何检查更新的文档是否真的被修改了?
【发布时间】:2021-06-24 13:06:02
【问题描述】:

我有一个“项目”集合,这是集合中的示例文档:

{ "id": 0, "price": 23.55 }

我正在更新编写一个更新商品价格的查询, 但想检查价格字段是否真的修改了。

例如,以下查询是合法的,但 实际上并没有修改文档。

db.collection('items').updateOne(
  { id: 0 },
  { $set: { price: 23.55 } }
);

有什么方法可以实现吗?

【问题讨论】:

  • 您使用的是哪个驱动程序? nodejs,猫鼬等?
  • @TusharGupta-curioustushar 这是 nodejs 驱动程序。

标签: node.js database mongodb mongodb-query


【解决方案1】:

updateOne会返回nModified,你可以知道文档是否被修改。

{  "n": 1,  "nModified": 1 }

https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#updateOne

https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~updateWriteOpCallback


https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#findOneAndUpdate

使用findOneAndUpdate 并将returnOriginal 设置为false,您将在回调中获得更新的文档。

const options = { returnOriginal: false; } // to return the updated document
findOneAndUpdate(filter, update, options, callback)

https://mongodb.github.io/node-mongodb-native/3.6/api/Collection.html#~findAndModifyCallback

从 findAndModify 命令返回的文档。如果没有找到文档,默认情况下 value 将为 null (returnOriginal: true),即使文档被更新;如果 returnOriginal 为 false,则在这种情况下将返回插入的文档。

【讨论】:

    猜你喜欢
    • 2017-12-12
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2015-02-10
    • 2015-11-22
    相关资源
    最近更新 更多