0

I have a unique index, because I want mongoDB to ignore any duplicates:

dbo.collection("sold").createIndex({ "myId": 1 }, { unique: true })

However, mongodb treats this as an error, meaning I have to create special error handlign in my application code:

catch(err){
  if(err.code === 11000){log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})}
  else{log( {err} )}
}

Is there some way to have mongodb not treat duplicates as an error?

Himmators
  • 14,278
  • 36
  • 132
  • 223
  • *"Is there some way to have mongodb not treat duplicates as an error?"* - No. A duplicate key error "is what it is". You either code to ignore the specific "expected" error code or "throw" on other unexpected codes, or you go with the overhead of using upserts instead. But you cannot "turn off" how the database basically functions. – Neil Lunn Nov 12 '18 at 00:35
  • Wil look in to upserts, thanks! – Himmators Nov 12 '18 at 20:02

0 Answers0