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

Mar*_* Sh 4 mongoose mongodb node.js

我有这个 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]
});
Run Code Online (Sandbox Code Playgroud)

当我尝试添加 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"
}
Run Code Online (Sandbox Code Playgroud)

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

wsc*_*rge 6

min并且max 并不意味着所提供的允许的数字量Number,如错误所示:

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

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

{
    type: Number,
    min : 101,
    max : 999
}
Run Code Online (Sandbox Code Playgroud)
  • 允许的最大值Number999
  • 允许的最小值Number101

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

{
    type: Number,
    min : 100000000,
    max : 999999999
}
Run Code Online (Sandbox Code Playgroud)