Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB NodeJS Driver: Duplicate key `E11000` extract index name

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?

like image 725
Mokhtar Avatar asked Mar 21 '26 00:03

Mokhtar


1 Answers

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.

like image 103
kevinadi Avatar answered Mar 23 '26 20:03

kevinadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!