Reputation: 10045
Is there a way to set custom error message for 'E11000 duplicate key error' in MongoDB?
(Preferably, using Mongoose):
userSchema.index({ name: 1, email: 1 }, { unique: true });
Upvotes: 6
Views: 4900
Reputation:
You can easily customize and display error messages for unique: true
validation errors using mongoose-beautiful-unique-validation
.
To do so simply use the package mongoose-beautiful-unique-validation:
npm install --save mongoose-beautiful-unique-validation
Then you can simply use it as a global plugin (as below) or per schema.
const beautifyUnique = require('mongoose-beautiful-unique-validation');
mongoose.plugin(beautifyUnique);
For full insight and reference, please see this comment and the Readme on GitHub.
You may also want to use the package mongoose-validation-error-transform for displaying Mongoose validation error message(s).
Upvotes: 5
Reputation: 3997
1) You can use mongoose-unique-validator.
https://www.npmjs.com/package/mongoose-unique-validator.
This makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB.
2) Referenced in What am I doing wrong in this Mongoose unique pre-save validation? you can also use pre save method in express
Schema.pre("save",function(next, done) {
//Here you can search if the record already exists and return custom message.
next();
});
Upvotes: 7
Reputation: 11671
No, not without changing the MongoDB source code and recompiling it with the new error message. You can swap out the message for one more to your liking with your application code. You could, for example, just wrap the index build call in a function that will return a different error message if a unique key constraint violation error occurs.
Upvotes: 2