[SOLVED] Mongoose validation failed: Path `value` (0) is less than minimum allowed value (0)

Hi,

I keep getting this error:

Item validation failed: specs.usedHands: Path `specs.usedHands` (0) is less than minimum allowed value (0).

I’m having problems with data validation using mongoose. My object schema looks sth similar to this:

const schema = new mongoose.Schema({
    type: {
        type: String,
        required: true,
        enum: [ ItemType.Armor, ItemType.Weapon ]
    },
    weaponType: {
        type: String,
        required: function () { return this.type === ItemType.Weapon }
    },
    armorType: {
        type: String,
        required: function () { return this.type === ItemType.Armor }
    },
    specs: {
        usedHands: { type: Number, min: function () { return this.type === ItemType.Weapon ? 1 : 0 }, max: 2 }
    },
})

And the object I’m validating is this:

const item = new Item({
        type: ItemType.Armor,
        armorType: ArmorType.Belt,
        specs: { usedHands: 0 }
    })

Even if I change item.specs.usedHands to 100 it will still say that 100 is less than the minimum (0)

I’m a bit confused…

Ok I replaced this with a custom validator and it’s working as it should:

        usedHands: {
            type: Number,
            validate: {
                validator: function (v) {
                    const min = this.type === ItemType.Weapon ? 1 : 0;
                    const max = this.type === ItemType.Weapon ? 2 : 0;
                    return min <= v && v <= max;
                },
                message: 'value should be between 0 and 2'
            }
        }