Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

513
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda