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

154
Visualizações
Mongoose .find() returns an empty array when searching by enum field

I have this schema:

const SoundSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    minFrec: {
        type: Number,
        required: true
    },
    maxFrec:{
        type: Number,
        required: true
    },
    minInt:{
        type: Number,
        required: true
    },
    maxInt:{
        type: Number,
        required: true
    },
    category: {
        type: String,
        lowercase: true,
        required: true,
        enum: ["Hogar", "Naturaleza", "Conversación", "Ocio", "Lugares", "Ciudad"]
    }
});

And I am trying to create this route to show all my items that match a certain category:

app.get("/sounds/:category", async (req, res) => {
const sounds = await Sound.find({ category: 'Ocio' }).sort({ name: 'asc'});
res.render("sounds/category", { sounds });
});

It does not work (returns an empty array) but it works if I filter by something without "enum" (name, minInt, etc).

I have done other routes that work, and I can find those items in mongo (db.sounds.find({category: "Ocio"})).

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your schema define the field category as lowercase: true which means the string will be saved in lower case (docs)

So you have to use lowercase into your query to match the exact value.

const sounds = await Sound.find({ category: 'ocio' }).sort({ name: 'asc'});

Or something more global:

const sounds = await Sound.find({ category: req.params.category.toLowerCase() }).sort({ name: 'asc'});

Even another option is to use $regex with option i like this example but it is a much more expensive option considering that your schema ensures that the field is lowercase. So to use toLowerCase() is a better option.

about 4 years ago · Juan Pablo Isaza 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