Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB unique index custom error message E11000

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 });
like image 470
eagor Avatar asked Oct 20 '14 08:10

eagor


1 Answers

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();
});
like image 156
Mangesh Pimpalkar Avatar answered Oct 31 '22 00:10

Mangesh Pimpalkar