1

I wanted to avoid creating duplicate documents, so upon searching how to do this, the first solution I found was this answer:

db.collection.update(doc, doc, {upsert:true})

But this is really slow compared to insertOne, so I looked to the second answer:

db.collection.createIndex( { propertyName: 1 }, {unique:true} )

This seems like a way better solution in terms of performance, but the problem is rather than just not inserting the duplicate, it throws an error:

(node:97200) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: main.dir index: path_1 dup key: { propertyName: "propertyName123" }

Is there a setting to make it not throw an error or do I need to use a try catch here?

J.Todd
  • 707
  • 1
  • 12
  • 34

1 Answers1

2

I don't think this is possible - if you take a look at the NodeJS MongoDB-driver source you can see that insertOne uses the underlying method executeOperation.

This method has a try catch around its actual execution of the statement and re-throws any error that might occur as you can see here. So afaik there's no way to "suppress" errors - you need to handle them yourself.

eol
  • 23,236
  • 5
  • 46
  • 64