首页 > 解决方案 > mongoose 文档 this.save 重复键 _id 错误

问题描述

我向 mongoose 添加了一个方法,该方法根据 req.body (express) 的输入更新产品。

我知道这是一种非常便宜的方式,但起初这是为 MVP 准备的。

const product = new Schema({
        //stuff
        gift: {
            from: {type: Date, required: false},
            to: {type: Date, required: false},
            active: {type: Boolean, required: true, default: false},
            index: false
        },
    },
    {
        minimize: false,
        timestamps: {createdAt: 'createdAt', updatedAt: 'updatedAt'}
    }
);

product.methods.updateAndSave = async function update(obj) {
    Object.assign(this, obj);
    await this.save();
};

得到错误:

Promise {
  <rejected> { BulkWriteError: E11000 duplicate key error collection: test.products index: _id_ dup key: { : ObjectId('5ad5eab958dde52d2c395ee2') }

这让我很困惑,因为没有_id_领域..​​....

数据发送:

{
    "gift": {
            "active": true,
            "to": "2018-07-01T21:59:59.000Z",
            "from": "2018-05-30T22:00:00.000Z"
        }
}

标签: node.jsmongodbmongoose

解决方案


我认为您正在尝试覆盖 mongoDB 中唯一字段的“_id”。你应该尝试以下。在您正在保存的“this”对象中,将旧 _id 作为新 _id,这样即使在您“覆盖它”后它也能保持价值

product.methods.updateAndSave = async function update(obj) {
Object.assign(this, obj);
await this.save();
};
//so in Object.assign(this, obj); you would put inside "this" your old _id as new _id

推荐阅读