Search code examples
javascriptnode.jsmongodbmongoose

Does MongoDB InsertMany returns both the successfully inserted and failed documents?


We're using MongoDB insertMany() and I'd like to get both the successfully inserted documents with the failed ones.

Some of the documents fail to be inserted since we first put the ones that are unique (by PhoneNumber) and after that if the code encounters the same PhoneNumber then it adds the string DUP to the phoneNumber.

The code :

try {
       await Leads.insertMany(leadsToInsert, {
        ordered: false
      });

}

catch(err) {

 if (err.code === 11000) {
        // Here we get the errors 
        const ordersIDsWithDuplicates = err.result.result.writeErrors;
 }

}

In the catch block we get the documents that failed.

Is there a way to get the documents that we successfully inserted , at the same time without querying the DB ?


Solution

  • Sure, it's under insertedIds on the same level with writeErrors:

    {
      "name":"BulkWriteError",
      "driver":true,
      "code":11000,
      "writeErrors":[ ... ],
      "writeConcernErrors":[ ... ],
      "insertedIds":[{"index":0,"_id":7085598},{"index":1,"_id":7085599} ... ]
    }