While using MongoDB NodeJS driver (or even mongoose), when inserting a new document, an E11000 error may return indicating a duplicate key collision has occurred.
What if the collection I am inserting into has multiple unique indices and I want to identify which one of them is hit (e.g. to notify the user the user that his username and/or email is already taken)?
This is the error raised after inserting a document with a colliding index:
{
"name": "MongoError",
"message": "E11000 duplicate key error index: db.users.$_id_ dup key: { : \"blucell\" }",
"driver": true,
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error index: db.users.$_id_ dup key: { : \"blucell\" }"
}
The only notion of the index causing the problem is in the message, which changes over time (already differs between mongo 2.x and 3.x).
Is there any more future-proof/easier way of checking which element/index is causing the collision?
Unfortunately there is no method as of MongoDB 3.4.7 that lists the colliding indexes in a separate, easy to parse field.
There is a discussion in Mongoose regarding this, but the solutions all rely on parsing the actual error message (see https://github.com/Automattic/mongoose/issues/2129).
Since the node driver just reports back the error given by the server, there is a MongoDB feature request for exactly this functionality (see SERVER-4637). I would suggest commenting/upvoting on the feature request to raise awareness of the issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With