mongoose: How to get index name on duplicate document 11000 error?
How can I get the index for which the error occurs with?
e.g. if my index is named email
, how do I get that from the err
object?
About this issue
- Original URL
- State: closed
- Created 10 years ago
- Reactions: 1
- Comments: 18 (1 by maintainers)
Here is my RegExp solution to get index name with any type of error syntax I have found:
Here what I have tested:
Thanks to @paambaati I got the functionality I needed.
But is there a terser way to get the same result? //cc @vkarpov15
Good job @alexbooker! There’s also another plugin for that, see #2284 and https://www.npmjs.com/package/mongoose-beautiful-unique-validation
The best way right now is by parsing the error message (slightly hacky, yes). The error message looks like:
E11000 duplicate key error index: test.x.$a_1 dup key: { : 1.0 }
Looks pretty consistent across mongodb server 2.4 and 2.6. The
index:
indicates which index causes the duplicate key error on the server side.