mongoose文件this.save重复键_id错误

时间:2018-06-19 10:03:50

标签: node.js mongodb mongoose

我添加了一种基于req.body(express)输入的mongoose方法来更新产品。

我知道这是一种非常便宜的方式,但这首先是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"
        }
}

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试覆盖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