Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

511
Views
Mongoose $inc with enum validation failed

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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!