【问题标题】:Mongoose Schema Validate for Async requestMongoose Schema 验证异步请求
【发布时间】:2018-04-13 21:41:50
【问题描述】:

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

代码 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 is not a function

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

这里没有错误。但是缺少验证,正在尝试插入记录。

我是猫鼬的新手。因此,请对答案稍加解释。

【问题讨论】:

  • 为什么不使用unique key 约束? (mongo docs)
  • 它没有锻炼,在谷歌搜索时我在 stackoverflow 中读到这种方法是可取的,因为唯一会设置索引属性。虽然我不确定这是什么意思,但我尝试了这个并让代码正常工作
  • 我不知道为什么使用验证器更可取有几个原因,主要是唯一键约束(它是一种特殊类型的索引)在使用验证器时总是会防止重复条目不是由于竞争条件(例如并发创建和/或更新会导致为不同记录存储相同的电子邮件地址)。

标签: mongoose mongoose-schema


【解决方案1】:

我得到了答案。我需要添加 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);
    });
}

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 2018-05-14
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 2017-10-11
    • 2015-09-14
    • 2018-10-09
    • 1970-01-01
    相关资源
    最近更新 更多