Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

514
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda