Mongoose unique and custom validation

888 views
Skip to first unread message

Lise K.

unread,
Dec 31, 2017, 5:22:59 PM12/31/17
to mongodb-user

I want to add validation with an error message for email being unique.

Here is my model


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');

If I try to save a email that is already in db, and I get

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?


Kevin Adistambha

unread,
Jan 17, 2018, 12:57:07 AM1/17/18
to mongodb-user

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

Reply all
Reply to author
Forward
0 new messages