MongoDB E11000 Unique Index Special Error Message

Is there a way to set a custom error message for 'E11000 duplicate key error' in MongoDB?
(Preferably using Mongoose):

userSchema.index({ name: 1, email: 1 }, { unique: true }); 
+5
source share
3 answers

1) You can use mongoose-unique-validator.

https://www.npmjs.com/package/mongoose-unique-validator .

This simplifies error handling, since you will receive a Mongoose validation error when you try to violate a unique constraint, and not an Mongolian E11000 error.

2) Link to What am I doing wrong in this unique Mongoose pre-check? you can also use the express pre-save method

 Schema.pre("save",function(next, done) { //Here you can search if the record already exists and return custom message. next(); }); 
+5
source

You can easily configure and display error messages for unique: true validation errors using mongoose-beautiful-unique-validation .

To do this, simply use the mongoose-beautiful-unique-validation package:

 npm install --save mongoose-beautiful-unique-validation 

Then you can simply use it as a global plugin (as shown below) or for each circuit.

 const beautifyUnique = require('mongoose-beautiful-unique-validation'); mongoose.plugin(beautifyUnique); 

See this comment and Readme on GitHub for full details and help.

You can also use the mongoose-validation-error-transform package to display Mongoose validation error messages.

+4
source

No, without changing the source code of MongoDB and recompiling it with a new error message. You can change the message text to your taste with your application code. You could, for example, simply wrap the call to build the index in a function that will return another error message if an error occurs that violates the unique key constraint.

0
source

Source: https://habr.com/ru/post/1205074/


All Articles