Mongoose/MongoDB 保存时抛出重复键错误?

Mongoose/MongoDB throwing duplicate key error on save?

根据MongoDB's documentation a call to save will create a new document, or update an existing document if _id is provided. Mongoose's documentation is less detailed,不讨论是否插入或更新。

我正在尝试使用 Mongoose 的 save 函数来更新文档,但我一直收到错误消息:

{"error":{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: staging.participants.$_id _ dup key: { : ObjectId('5515a34ed65073ec234b5c5f') }"}}

Mongoose 的 save 函数是否像 MongoDB 的 save 函数一样执行更新插入,还是只是执行插入?

定义 save 是插入还是更新的是 isNew 标志,您可以 see here.

当从 find 查询(或其任何变体)返回文档实例时,此标志自动设置为 false。如果您手动实例化文档,请尝试在保存之前将此标志设置为 false:

var instance = new Model({ '_id': '...', field: '...' });
instance.isNew = false;
instance.save(function(err) { /* ... */ });

还有一个 init 函数,它将初始化文档和 automatically set isNew to false:

var data = { '_id': '...', field: '...' };
var instance = new Model();
instance.init(data, {}, function(err) {
    instance.save(function(err) { /* ... */ })
});