Javascript 架构id设置为false的Mongoose findOneAndUpdate

Javascript 架构id设置为false的Mongoose findOneAndUpdate,javascript,node.js,mongodb,mongoose,mongoose-schema,Javascript,Node.js,Mongodb,Mongoose,Mongoose Schema,通常,我会搜索/查找文档。如果找到文档,我会更新它。。。如果没有找到,我会创建它 我正在寻找一种更有效的方法来做到这一点,通过阅读文档——我已经拼凑了以下内容(我也在使用hapi.js) 。。。。ProductSchema已导出,并且需要作为“产品”。。它用于创建新产品。我传递我的有效载荷(已经通过Joi验证) upsert:true-如果未找到,则表示创建 new:true-返回新创建或更新的文档( 结果) runValidators:true-应该强制根据模式验证数据(产品) 然而,我在

通常,我会搜索/查找文档。如果找到文档,我会更新它。。。如果没有找到,我会创建它

我正在寻找一种更有效的方法来做到这一点,通过阅读文档——我已经拼凑了以下内容(我也在使用hapi.js)

。。。。ProductSchema已导出,并且需要作为“产品”。。它用于创建新产品。我传递我的有效载荷(已经通过Joi验证)

  • upsert:true-如果未找到,则表示创建
  • new:true-返回新创建或更新的文档( 结果)
  • runValidators:true-应该强制根据模式验证数据(产品)
然而,我在实例化产品时遇到了一个问题——Mongoose会自动插入一个“\u id”

“_id”是不可变的。因此,当我尝试更新时,会出现以下错误:

{ MongoError: After applying the update to the document {_id: ObjectId('59cc33812e36f3d0272dc28e') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('59cc3c21e0938d99c2716989')
所以,我的第一个想法是-使用文字符号创建对象。。。然后我可以控制省略“_id”

但是,这样做意味着该对象不是由模式创建/验证的

然后我读到,您可以通过在模式中将_id设置为false来禁止创建一个_id。我这样做了,现在得到了一个没有_id验证的对象。更新/创建现在可以正常工作,不会抛出错误

抑制模式中的“_id”字段似乎不是什么问题,因为Mongo服务器总是为每个条目创建一个新的_id。我使用SKU作为我的唯一密钥

然而,我意识到,我是通过四处打探并试图弄明白事情的真相才来到这里的

所以我的问题的核心是——我的方法有缺陷吗

     let product = new Products(request.payload);

        Products.findOneAndUpdate(
            { sku : request.payload.sku }, 
            {$set: product },
            { upsert: true,  new: true, runValidators: true },
            function(err, result) {
            if (err) {
                console.error(err);
                return reply(Boom.badRequest('Error saving product'));
            }

            return reply(result); 

        });
{ MongoError: After applying the update to the document {_id: ObjectId('59cc33812e36f3d0272dc28e') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('59cc3c21e0938d99c2716989')