modifiedCount 为 1,即使文档没有更改

modifiedCount is 1 even though the document didn't change

我正在使用一个简单的 updateOne 查询,我从数组中提取一个 ObjectId。

await this.portfolioModel.updateOne(
  {
    _id: portfolioId,
    'watchlist.custom._id': watchlistId
  },
  {
    $pull: {
      'watchlist.custom.$.assets': assetId
    }
  }
)

但我想检测文档是否实际更改,或者 assetIds 是否不在数组中。问题是即使文件没有改变 MongoDB 仍然 returns modifiedCount1.

{
  acknowledged: true,
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1
}

我检查了文档,__v 没有随着更新而增加,所以我不知道为什么 MongoDB 认为文档已更改。

这是文档的外观(更新前后):

{
  "_id": {
    "$oid": "600188dab0b1c70050084e3e"
  },
  "watchlist": {
    "all": [],
    "custom": [
      {
        "assets": [],
        "_id": {
          "$oid": "624d7a18c89b3937212b3a55"
        }
      }
    ]
  },
  "__v": 18,
  "createdAt": {
    "$date": "2021-05-11T22:19:05.450Z"
  },
  "updatedAt": {
    "$date": "2022-04-06T11:45:37.415Z"
  }
}

我在使用 mongoose 6.3.5 和 MongoDB 无服务器版本 5.3.1 时遇到了同样的问题。

我的解决方法是从我的架构中删除 {timestamps: true}。这会导致文档为 'modified',即使未对其值进行更改也是如此。我相信这是因为 'updatedAt' 值会在 updateOne() 访问文档时发生变化。