我正在使用node和mongodb 5。我在集合的Parcel属性中添加了一个唯一索引。当我在测试时运行程序时,我得到:
MongoBulkWriteError: E11000 duplicate key error collection: mydata.pima2 index: Parcel_1 dup key: { Parcel: "AARON" }
我的代码:
for (let j = 0; j < lastNameRecords.length; j++) {
const ln = lastNameRecords[j].name;
const recordsObj = { 'Parcel': ln, 'recordNum': 'TBD' };
recordsArr.push(recordsObj);
}
console.log('number of records: ', recordsArr.length);
try {
--> const response = await collection.insertMany(recordsArr, { ordered: false });
const updated = await collection.updateOne(result, { recordNum: 'ERD' });
} catch (error) {
console.log(error);
}
错误发生在上面有箭头的那一行。显然,在测试时,我正在插入多条记录,所有这些记录以前都已插入到“pima2”集合中。我希望避免导致错误或处理它,以便可以继续执行下一条语句
考虑到这里最好的方法可能是upsert,我决定改变
const response = await collection.insertMany(recordsArr, { ordered: false });
型
我对https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/感到困惑。我尝试过
const response = await collection.updateMany({}, recordsArr, { upsert: true });
但是现在得到了标题中的错误。我该如何修复这个错误?
更新:
我还没有定义模式,但我的pima2集合中的一个记录的屏幕截图如下:
1条答案
按热度按时间sd2nnvve1#
在我看来,在你的
Schema
中,你把Parcel
和选项unique: true
放在一起,如果这样的话,所有的值都应该是唯一的。大多数时候,如果我遇到这个问题,情况就是这样,如果你能为你的集合添加Schema
,让我们看看是否能解决这个问题;- )