我正在尝试编写验证功能来检查电子邮件的唯一值。
代码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');
我收到错误消息 TypeError:fn不是函数
代码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;
});
}
这里没有错误。但缺少验证并且记录正试图插入。
我是猫鼬新手。所以请回答一下。
答案 0 :(得分:0)
我得到了答案。我需要添加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);
});
}