node.js - 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"
}
}
解决方案
我认为您正在尝试覆盖 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
推荐阅读
- macos - 如何删除某个目录(在 Mac 终端中)-unix 中文件名的最后 n 个字符?
- java - 无法从 Jenkins 将工件部署到 Nexus 存储库
- python - 计算for循环中的迭代次数
- google-cloud-platform - Spark HBase 到 Google Dataproc 和 Bigtable 的迁移
- c++ - 如何通过指向非易失性的指针接收易失性?
- java - java多态的困惑
- java - 如何添加和遍历 LinkedList (Java)
- java - 如何更新线程中的引用和活动?
- bash - 如果前一行是前缀,则删除行(从输出中省略)
- python - 即使使用 pip 成功安装后,也没有名为“cv2”的模块