【问题标题】:Mongo: updating document and adding/updating lastModifiedMongo:更新文档和添加/更新 lastModified
【发布时间】:2020-05-06 00:02:15
【问题描述】:

我需要更新一个匹配 item.id 的文档

更新文档的字段存储在对象项中

查询:

bulk.find({ id: item.id }).upsert().updateOne({ $set: item, $currentDate : {lastModified: true} })

{$set: item} - 完成这项工作并将项目中的所有字段添加到文档中,但是当我添加 $currentDate 字段时,mongo 返回:

 errmsg: "Updating the path 'lastModified' would create a conflict at 'lastModified'",

我应该只做 item.lastModified = (new Date()).getTime(),还是可以通过查询来做?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    这是一个 Mongo 功能错误。在单个操作中,您不能多次更改单个文件。 $set - 设置变量 lastModified 然后 $currentDate 尝试立即修改它。解决方案是在对象item中添加lastModified

    item.lastModified = new Date()
    bulk.find({ id: item.id }).upsert().updateOne({ $set: item })
    

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2018-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-22
      相关资源
      最近更新 更多