Node.js Mongoose架构编号字段的长度要精确

Node.js Mongoose架构编号字段的长度要精确,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我有一个月亮鹅模式: var userSchema = new mongoose.Schema({ firstname: { type: String, required: true, min: 3, max: 24 }, lastname: { type: String, required: true, min: 3, max: 24

我有一个月亮鹅模式:

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"
}
是否有其他方法来验证
数字
类型字段的精确长度?
还是我误解了mongoose存储数字的方式?

min
max
不表示提供的
数字中允许的位数,如错误所示:

(320981350)大于最大允许值

它们的意思是
Number
类型字段的实际最小/最大值,例如

{
    type: Number,
    min : 101,
    max : 999
}
  • 允许的最大
    数量为
    999
  • 允许的最小
    数量为
    101
在您的情况下,如果您有9位数字作为
id
,请在模式中定义字段,如下所示:

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

min
max
并不意味着
min length
max length

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

{
    type: Number,
    min: 100000000,
    max: 999999999
}
看一下mongoose文档: