当我使用 mongoose 的 findOneAndUpdate 方法时,为什么 mongoose 会更改 _id ?

Rom*_*usa 5 mongoose mongodb node.js

我来自关系数据库,而主键(本例中为 _id)在其生命周期中是相同的,因此当我在 mongodb 中看到这种行为时,我感到很惊讶。

我按以下方式使用猫鼬的 findOneAndUpdate 插件方法:

User.findOneAndUpdate(
  { "products._id": _id, "_id": req.payload._id },
  {
    $set: {
      "products.$": { name: "New name" },
    },
  },
  {
    new: true,
    runValidators: true,
  },
  function (err, doc) {
    if (err != null) {
      res
        .status(500)
        .json({
          message: "Error on updating. Please, try again later.",
        });
    } else if (doc == null) {
      res.status(404).json({ message: "Product not found." });
    } else {
      res.status(200).json(doc.products);
    }
  }
);
Run Code Online (Sandbox Code Playgroud)

开始之前:

{_id: 58b5e637f9f904a800721abf, name: "Old name"}
Run Code Online (Sandbox Code Playgroud)

(_id 更改)之后:

{_id: 58b5e35a7f4ff38c433a5bc9, name: "New name"}
Run Code Online (Sandbox Code Playgroud)

我只想在更新后保留相同的 _id ,因为我认为当我实现同步更新时我可能会遇到麻烦。

我搜索了一下,发现这个 mongoose 方法对于 mongo 的驱动程序来说是直接调用的,不需要中间件。因此,我想这个问题可以由 mongodb 专家在没有 mongoose 知识的情况下解决。

Nod*_*ode 5

_id附加到文档修订版,而不是文档实体。

通过传递,new: true您要求 Mongo 返回最新版本的 id,该版本的 id 与原始文档(Upsert)不同。

对于基于文档的存储,建议实现您自己的 UUID 架构。

要么使用uuid确定性:

var UUID = require('uuid-1345');

UUID.v3({
  namespace: UUID.namespace.oid,
  name: "abc" // Some formula to calculate you uuid, could be based on the document's legacy id or some other unique identifier.
}, function (err, id) {
  console.log("Generated a name-based UUID using MD5:\n\t%s\n", id);
});
Run Code Online (Sandbox Code Playgroud)

或者使用普通随机十六进制随机:

var crypto = require('crypto');

var id = crypto.randomBytes(20).toString('hex');
Run Code Online (Sandbox Code Playgroud)

将此包含在您的文档正文中...并且不要忘记对其进行索引