I am struggling with mongoose.
I have a filter that I want to use to search through my model, which is:
const recipeSchema = new Schema(
{
name: { type: String, required: [true, "Recipe must have a name"] },
category: {
type: ObjectId,
ref: "Category",
required: [true, "Recipe must belong to a category"],
},
difficulty: { type: String, enum: ["easy", "medium", "hard"] },
}
);
I got it to work by using this code:
let recipes = await Recipe.find({ ...searchTerm });
if (difficulty) {
recipes = await Recipe.find({
...searchTerm,
difficulty: { $in: difficulty.split(",") },
});
}
if (category && category !== "all") {
recipes = await Recipe.find({
...searchTerm,
category: { $in: category.split(",") },
difficulty: { $in: difficulty.split(",") },
});
}
Can this code be simplified and use conditional logic inside queries?