So according to the mongoose docs, you are supposed to be able to set a custom error message in the schema like so:
var breakfastSchema = new Schema({
eggs: {
Thanks for all answers, I've figured out my problem.
My schema is like that.
var User = new Schema({
username: {type: String, required: [true, "Username is required"], unique: true},
email: {type: String, required: [true, "Email is required"], unique: true},
password: {type: String, required: true, unique: false},
});
I recommend to use like a function.
You can use like this;
User.post("save", function (error, doc, next) {
if (error.keyValue.email != null && error.name === "MongoError" && error.code === 11000) {
console.log("Email must be unique");
} else if (error.keyValue.username != null && error.name === "MongoError" && error.code === 11000) {
console.log("Username must be unique");
} else {
console.log("not found any idea, search for another reasons");
}
});
you can add a custom async validator. for example:
{
validator: (value) => {
return UserModel.findOne({ email: value })
.then(user => Promise.resolve(user == null))
.catch(error => Promise.reject(false));
},
message: "User with this email already exists"
}