【问题标题】:Mongoose validate only one pathMongoose 只验证一条路径
【发布时间】:2022-06-29 14:16:57
【问题描述】:

我有以下长架构:

const mySchema = new mongoose.Schema({
  // some stuff, firstName, lastName ... etc
  password: {
    type: String,
    minLength: 8,
    maxLength: 120,
  }
})

我在其中一条路线内,我只想对提交的密码进行验证。 我可以在 Mongoose 中做些什么,例如:

mySchema.fields.password.validate("123") // Error: password is less than 8 characters!

有类似的吗?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    使用猫鼬自定义验证器 https://mongoosejs.com/docs/validation.html#custom-validators

    例子-

    const mySchema = new mongoose.Schema({
        // some stuff, firstName, lastName ... etc
        password: {
            type: String,
            minLength: 8,
            maxLength: 120,
            validate: {
                validator: function (v) {
                    //do something, return false if something wrong
                    return /^[A-Za-z0-9_]+$/.test(v);
                }
            }
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-05
      相关资源
      最近更新 更多