Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

Mongoose Schema Validate for Async request

I am trying to write validation function to check unique value for email.

Code 1

userSchema.path('email').validate(function (email, fn) {
    const User = mongoose.model('User');
    if (this.isNew || this.isModified('email')) {
      User.find({ email: email }).exec(function (err, users) {
        fn(!err && users.length === 0);
      });
    } else fn(true);
  }, 'Email already exists');

I am getting an error message TypeError: fn is not a function

Code 2

var emailValidators = [
    {validator:uniqueEmailValidator, message:"Email is registered with us"},
    {validator:emailRegexValidator, message:"Email is not in valid format"}
];



function uniqueEmailValidator(value){
  return this.model('User').count({email:value}, function(err, count){
        if(err || count){
            console.log(count); // I can see this console
            return false;
        }
        return true;
    });
}

No errors here. But validation is missing out and the record is trying to insert.

I am new to mongoose. So please be little explanatory on the answer.

Upvotes: 0

Views: 626

Answers (1)

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6887

I got the answer. I need to add isAsync:true and so i will get the callback function in my validator

var emailValidators = [
    {isAsync: true, validator:uniqueEmailValidator, message:"Email is registered with us"},
    {validator:emailRegexValidator, message:"Email is not in valid format"}
]

function uniqueEmailValidator(value, cb){

  return this.model('User').count({email:value}, function(err, count){
        if(err || count){
            return cb(false);
        }
        return cb(true);
    });
}

Upvotes: 1

Related Questions