Performance: let MongoDB return errors instead of preventing them

Hello @Thomas_Perrin, welcome to the MongoDB Community forum!

I think the single call to the database is the correct way to handle the above functionality.

Here is what I had tried (this is using native MongoDB NodeJS Driver API):

try {
	insertResult = await collection.insertOne(doc)
}
catch(err) {
	if (err instanceof MongoServerError && err.code === 11000) {
		console.error("# Duplicate Data Found:\n", err)
		insertResult = { 
			insertedId: null,
			message: "Message expalining the situation."
		}
	}
	else {
		throw new Error(err)
	}
}

The MongoDB NodeJS Driver Error classes has MongoServerError as one of its sub-classes. The "E11000 duplicate key error collection" is defined as one of the errors as MongoServerError.

Also see:

1 Like