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"] },
}
);
Category can be either all
for all categories, or a specific id
.
Difficulty can be either []
for all difficulties, or a specific difficulty defined above.
Right now I have this, which semi works:
if (category !== "all") {
recipes = await Recipe.find({ ...searchTerm })
.where("category")
.equals(category)
.where("difficulty")
.equals(difficulty)
.exec();
} else {
recipes = await Recipe.find({ ...searchTerm });
}
I know why the above code doesn’t work as I want it, I just don’t know how to get it to do what I want.
So the above works only if a category is selected (can’t be all obviously) and if there is exactly one item in the array, if the array is empty it doesn’t work.
I would like it to search irrespective of category if all is selected for category, and irrespective of difficulty is the difficulty is []
, but also be able to filter based on more than one difficulty.
Help please?