小编Rom*_*usa的帖子

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

我来自关系数据库,而主键(本例中为 _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 更改) …

mongoose mongodb node.js

5
推荐指数
1
解决办法
1913
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1