Mongoose Schema 数字字段的长度要准确

问题描述 投票:0回答:3

我有这个 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 为 111222333 的新用户时,我收到下一个验证错误:

{
   "errors": {
        "id": {
            "message": "Path `id` (111222333) 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": 111222333
            },
            "kind": "max",
            "path": "id",
            "value": 111222333,
            "$isValidatorError": true
        }
    },
    "_message": "User validation failed",
    "message": "User validation failed: id: Path `id` (111222333) is more than maximum allowed value (9).",
    "name": "ValidationError"
}

是否有其他方法来验证

Number
类型字段的长度是否准确? 还是我误解了猫鼬存储数字的方式?

node.js mongodb mongoose
3个回答
6
投票

min
max
do not 表示所提供的
Number
中允许的数字数量,如错误所示:

(320981350)大于最大允许值(9)

它们的意思是具有

Number
类型的字段的实际最小/最大值,例如在

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

在您的情况下,如果您的

id
有 9 位数字,请在架构中定义字段,如下所示:

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

2
投票

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

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`
        }
    }
   
})

了解更多关于自定义验证


1
投票

min
max
并不意味着
min-length
max-length
...

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

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

看看猫鼬文档: 猫鼬文档

© www.soinside.com 2019 - 2024. All rights reserved.