Marik Sh
Marik Sh

Reputation: 731

Mongoose Schema number field to be at exact length

I have this moongoose schema:

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]
});

when I try to add a new user with the id 111222333 I get the next validation error:

{
   "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"
}

Is there any other way to validate a Number type field to be in an exact length? or did I misunderstood the way mongoose stores numbers?

Upvotes: 4

Views: 10579

Answers (3)

RmK
RmK

Reputation: 1438

Another option is to write a custom validator

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

Read more about custom validations

Upvotes: 2

N-Alpr
N-Alpr

Reputation: 336

min or max does not mean min-length or max-length ...

So to achieve your goal you better set this as your schema:

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

take a look at mongoose documentation: mongoose Doc

Upvotes: 1

wscourge
wscourge

Reputation: 11291

min and max do not mean allowed amount of digits in the Number provided, as the error say:

(320981350) is more than maximum allowed value (9)

What they mean is an actual minimum / maximum value of the field with Number type, so for example in

{
    type: Number,
    min : 101,
    max : 999
}
  • the maximum Number allowed is 999
  • the minimum Number allowed is 101

In your case, if you have 9-digit numbers as your id, define the field in schema like:

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

Upvotes: 6

Related Questions