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"}))
.
CodePudding user response:
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.