【问题标题】:Validation in mongoose Schemamongoose Schema 中的验证
【发布时间】:2020-07-26 18:13:39
【问题描述】:

我正在为 mongoose 中的用户模式条目编写验证。我想在架构中创建两个条目(密码、googleId)中的任何一个,但不是两个条目都是必需的。我想确保用户有密码或 googleId。如何做到这一点?以下是我的架构

const UserSchema = new mongoose.Schema({
    password: {
        type: String,
        trim: true,
        required: true,
        validate: (value)=>
        {
            if(value.includes(this.uname))
            {
                throw new Error("Password must not contain username")
            }
        }
    },
    googleId: {
        type: String,
        required: true
    }
});

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您可以使用custom validator

    const UserSchema = new mongoose.Schema({
        password: {
            type: String,
            trim: true,
            required: true,
            validate: {
                validator: checkCredentials,
                message: props => `${props.value} is not a valid phone number!`
            },
        },
        googleId: {
            type: String,
            required: true
        }
    });
    
    
    function checkCredentials(value) {
       if (!this.password || !this.googleId) {
           return false;
       }
       return true; 
    }
    
    
    
    

    或使用pre 验证中间件

    UserSchema.pre('validate', function(next) {
        if (!this.password || !this.googleId) {
            next(new Error('You should provide a google id or a password'));
        } else {
            next();
        }
    });
    

    【讨论】:

      【解决方案2】:

      您可能会做的是添加一个预验证检查,然后调用 next 或使文档无效。

      const schema = new mongoose.Schema({
          password: {
              type: String,
              trim: true
          },
          googleId: {
              type: String
          }
      });
      
      schema.pre('validate', { document: true }, function(next){
          if (!this.password || !this.googleId)
              this.invalidate('passwordgoogleId'. 'One of the fields required.');
          else
              next();
      });
      

      我还没试过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-05-29
        • 2018-10-09
        • 1970-01-01
        • 2017-10-31
        • 2018-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多