I’m working with node and mongodb 5. I have a unique index added to the Parcel property of my collection. As I run the program while testing, I get:
MongoBulkWriteError: E11000 duplicate key error collection: mydata.pima2 index: Parcel_1 dup key: { Parcel: "AARON" }
My code:
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);
}
Th error is occurring at the line with the arrow above. Obviously as I test, I am inserting multiple records , all of which have been previously inserted into the ‘pima2’ collection. I want to avoid causing an error or handle it so that I can move on to the next statement
Thinking that maybe the best approach here is an upsert, I have decided to change
const response = await collection.insertMany(recordsArr, { ordered: false });
I am confused about https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/ . I’d tried
const response = await collection.updateMany({}, recordsArr, { upsert: true });
but now getting the error in the title. How do I fix this?