Home > Software design >  Mongoose $inc with enum validation failed
Mongoose $inc with enum validation failed

Time:03-09

I'm working with featherJs and mongoose. I have a schema with an enum which I want to $inc.

new Schema({
    status: { type: Number, enum: [0, 1, 2, 3], default: 0 },
});

But when I $inc the 'status' field, it doesn't care about the enum, I can $inc as many times I want and get a status to 100000.

I don't know if it's because of featherjs or something else

Thanks

CodePudding user response:

This is "working as intended", as specified in the docs:

enum: Array, creates a validator that checks if the value is strictly equal to one of the values in the given array.

So enum just creates a mongoose validator, that is:

Validation is middleware. Mongoose registers validation as a pre('save') hook on every schema by default.

In theory you should be using their update validators for this, however $inc is not supported by them, and in addition their behavior is not quite clear at times.

I personally would recommend not to use mongoose at all, it's a black box that only adds bugs and confusion. specifically when it comes to their "validators" which are not "real" validators.


So what can you do to fix this?

  1. The easiest solution is to just do it in code, first find the object and if it fits the criteria only then do the $inc, obviously this does not give actual validation and is only supported where you'd implement it, if you have many places in the code where such update can occur this is also not optimal.

  2. use mongodb validation, this is "real" validation that actually validates at the db level. For example you could create your collection:

db.createCollection('collection_name', {
    validator: {
        $jsonSchema: {
            bsonType: 'object',
            properties: {
                status: {
                    bsonType: 'int',
                    enum: [0, 1, 2, 3],
                    description: 'must be a valid status integer',
                },
            },
        },
    },
    validationAction: 'error',
});

Now any update with a none valid value will fail.

  • Related