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 });
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();
});
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