Mongoose Schema验证异步请求

时间:2021-12-30 19:39:54

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

我正在尝试编写验证功能来检查电子邮件的唯一值。

Code 1

代码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

我收到一条错误消息TypeError:fn不是一个函数

Code 2

代码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.

我是猫鼬的新手。所以请对答案稍作解释。

1 个解决方案

#1


0  

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

我得到了答案。我需要添加isAsync:true,所以我将在我的验证器中获得回调函数

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

#1


0  

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

我得到了答案。我需要添加isAsync:true,所以我将在我的验证器中获得回调函数

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