mongodb 蒙戈无效参数错误:在尝试upsert期间,更新文档需要原子运算符

qqrboqgw  于 2022-12-18  发布在  Go
关注(0)|答案(1)|浏览(138)

我正在使用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集合中的一个记录的屏幕截图如下:

sd2nnvve

sd2nnvve1#

在我看来,在你的Schema中,你把Parcel和选项unique: true放在一起,如果这样的话,所有的值都应该是唯一的。大多数时候,如果我遇到这个问题,情况就是这样,如果你能为你的集合添加Schema,让我们看看是否能解决这个问题;- )

相关问题