Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors with bulkinsert in Mongo NodeJS [duplicate]

I'm using NodeJS with MongoDB and Express. I need to insert records into a collection where email field is mandatory. I'm using insertMany function to insert records. It works fine when unique emails are inserted, but when duplicate emails are entered, the operation breaks abruptly.

I tried using try catch to print the error message, but the execution fails as soon as a duplicate email is inserted. I want the execution to continue and store the duplicates. I want to get the final list of the records inserted/failed.

Error Message:

Unhandled rejection MongoError: E11000 duplicate key error collection: testingdb.gamers index: email_1 dup key: 

Is there any way to handle the errors or is there any other approach apart from insertMany?

Update:

Email is a unique field in my collection.

like image 265
Anirudh Avatar asked Oct 04 '17 07:10

Anirudh


1 Answers

If you want to continue inserting all the non-unique documents rather than stopping on the first error, considering setting the {ordered:false} options to insertMany(), e.g.

db.collection.insertMany( [ , , ... ], { ordered: false } )

According to the docs, unordered operations will continue to process any remaining write operations in the queue but still show your errors in the BulkWriteError.

like image 61
Nic Cottrell Avatar answered Oct 24 '22 07:10

Nic Cottrell