【问题标题】:MongoInvalidArgumentError: Update document requires atomic operators during attempted upsertMongoInvalidArgumentError:更新文档在尝试更新插入期间需要原子运算符
【发布时间】:2022-12-14 22:57:39
【问题描述】:

我正在使用 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”集合中。我想避免导致错误或处理错误,以便我可以继续执行下一条语句

认为这里最好的方法可能是更新,我决定改变

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 });

但现在标题中出现错误。我该如何解决?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      相关资源
      最近更新 更多