I want to add validation with an error message for email being unique.
Here is my model
If I try to save a email that is already in db, and I get
var mongoose = require('mongoose'); //V 3.6.1 // User Schema var UserSchema = mongoose.Schema({ username: { type: String, required: true }, email: { type: String, index: true, unique: true, required: true, uniqueCaseInsensitive: true }, password: { type: String, required: true } }); UserSchema.path('email').validate(function(value, done) { this.model('User').count({ email: value }, function(err, count) { if (err) { return done(err); } // If `count` is greater than zero, "invalidate" done(!count); }); }, 'Email already exists');
DeprecationWarning: Implicit async custom validators (custom validators that take 2 arguments) are deprecated in mongoose >= 4.9.0. events.js:183 throw er; // Unhandled 'error' event ^ ValidationError: User validation failed: email: Email already exists
What I need is to wrapp this error into ValidationError and display the error in the form when I call validate or save .
does anyone know how to do it?
Hi Lise
It may be easier and more performant to use MongoDB’s unique index; see Unique Index for more information. If you create a unique index on the email
field, MongoDB will return an error should you attempt to insert an existing email.
There is some example code in mongoose’s Validation page under the heading The unique Option is Not a Validator
.
Best regards
Kevin