Mongoose Schema编号字段的长度准确

时间:2017-10-18 09:30:11

标签: node.js mongodb mongoose

我有这个moongoose架构:

var userSchema = new mongoose.Schema({
    firstname: {
        type: String,
        required: true,
        min: 3,
        max: 24
    },

    lastname: {
        type: String,
        required: true,
        min: 3,
        max: 24
    },

    id: {
        type: Number,
        required: true,
        min: 9,
        max: 9
    },

    mediations: [assetSchema]
});

当我尝试添加ID 320981350 的新用户时,我收到下一个验证错误:

{
   "errors": {
        "id": {
            "message": "Path `id` (320981350) is more than maximum allowed value (9).",
            "name": "ValidatorError",
            "properties": {
                "max": 9,
                "type": "max",
                "message": "Path `{PATH}` ({VALUE}) is more than maximum allowed value (9).",
                "path": "id",
                "value": 320981350
            },
            "kind": "max",
            "path": "id",
            "value": 320981350,
            "$isValidatorError": true
        }
    },
    "_message": "User validation failed",
    "message": "User validation failed: id: Path `id` (320981350) is more than maximum allowed value (9).",
    "name": "ValidationError"
}

还有其他方法可以验证Number类型字段的长度是否合适? 还是我误解了猫鼬储存数字的方式?

3 个答案:

答案 0 :(得分:2)

minmax 表示所提供的Number中允许的位数,正如错误所示:

  

(320981350)超过允许的最大值(9)

它们的含义是Number类型字段的实际最小值/最大值,例如在

{
    type: Number,
    min : 101,
    max : 999
}
  • 允许的最大Number999
  • 允许的最小Number101

在您的情况下,如果您的id有9位数字,请在架构中定义字段,如:

{
    type: Number,
    min : 100000000,
    max : 999999999
}

答案 1 :(得分:0)

minmax并不代表min-lengthmax-length ......

为了实现您的目标,您最好将其设置为您的架构:

{
    type: Number,
    min: 100000000,
    max: 999999999
}

看看mongoose文档: mongoose Doc

答案 2 :(得分:0)

另一种选择是编写自定义验证器

const userSchema = new mongoose.Schema({
    id: {
        type: Number,
        required: true,
        validate: {
            validator: function(val) {
                return val.toString().length === 9
            },
            message: val => `${val.value} has to be 9 digits`
        }
    }
   
})

详细了解custom validations