Node.js 为什么mongodb在使用findOneAndUpdate方法时会更改_id?

Node.js 为什么mongodb在使用findOneAndUpdate方法时会更改_id?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我来自关系数据库,而主键(本例中为_id)在其生命周期中是相同的,因此当我在mongodb中看到这种行为时,我感到惊讶 我以以下方式使用mongoose的findOneAndUpdate插件方法: User.findOneAndUpdate( { "products._id": _id, "_id": req.payload._id }, {

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

我以以下方式使用mongoose的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)
                            }
                        }
                    );
开始前:

{_id: 58b5e637f9f904a800721abf, name: "Old name"}
之后(id已更改)

{_id: 58b5e35a7f4ff38c433a5bc9, name: "New name"}
我只想在更新后保持相同的_id,因为我想我在实现同步更新时可能会遇到麻烦


我搜索了一下,发现这个mongoose方法对mongo的司机来说是直截了当的,没有中间工具。因此,我想mongodb的专家可以在不了解mongoose的情况下解决这个问题。

\u id
附在文档修订版上,而不是文档实体上

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

对于基于文档的存储,建议实现自己的UUID模式

选择以下选项之一:

或随机与普通随机十六进制:

var crypto = require('crypto');

var id = crypto.randomBytes(20).toString('hex');

将此内容包含在文档的正文中。。。别忘了去做

在我看来,它创建了一个新条目。为什么您的文档没有
产品
部分?你能告诉我你想要实现什么吗?当然。这是一个1对N的关系,而用户(商店,在现实世界中)可以有N个产品,而产品有一个用户(商店)
var crypto = require('crypto');

var id = crypto.randomBytes(20).toString('hex');