如何在猫鼬中定义字符串数组?

时间:2018-09-29 18:08:59

标签: node.js mongoose mongoose-schema

我想将文档定义为

cordova emulate android --target="the name"

数字不应以0开头,长度应为5。另外,元素数最少应为1

我在这种类型的东西中定义的猫鼬模式

numbers : ["99995", "44444", "666664".....]

但是我应该如何检查数字长度,即至少需要一个数字?

3 个答案:

答案 0 :(得分:0)

“当您创建自定义验证器时,您可以在函数中执行任何操作来验证数据。只有通过验证后,您才必须返回true,如果失败则必须返回false。”

validator: (num) => {
    if(num.length == 5) {
         return /[1-9]{1}\d{4}/.test(num); // You forgot to add / at the end of the RegEx
    }
    return false;
}

或者您可以使用match通过正则表达式验证字符串,而不用创建自己的函数

numbers: {
     type: [String], match: /^[^0]\d{4}$/
}

答案 1 :(得分:0)

尝试required: true

validate: {
    validator: function(values) { 
       // Write validator for each value
    },
    message: "add a custom message"
},
required: [true, "numbers cannot be empty"]

答案 2 :(得分:0)

这应该对您有用:

numbers: [{
    type: String,
    length: 5,
    required: [true, 'Why no numbers?'],
    validate: {
      validator: function(num) {
        return /^[1-9]{1}\d{4}$/.test(num);
      },
      message: props => `${props.value} is not a valid phone number!`
    },
  }]

它强制至少一个元素(通过required),并确保您只能保存一个字符串,该字符串以大于0的数字开头,具有4个以上的字符,并且长度恰好为5个字符(通过自定义validate function,它使用regEx进行测试。