I have the following schema:
const RecipeSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
ingredients: [
{
name: {
type: String,
required: true,
trim: true
},
amount: {
type: Number,
required: true
}
}
]
});
const Recipe = mongoose.model('Recipe',RecipeSchema);
export {Recipe as default}
I am stuck on filtering the recipes by providing two numbers: min and max, and return the list of recipes that have the number of ingredients ( length of ingredients array ) greater than min and less than max. Can you help me on this one?
CodePudding user response:
here I have used the $expr operator to filter out all those documents which have sizes greater than or equal to min and less than or equal to max.
let min = 1
let max = 2
RecipeModel.find({"$expr":{$gte:[{$size:"$ingredients"},min], $lte:[{$size:"$ingredients"},max]}})
CodePudding user response:
This sequence finally did it
{$where: "this.ingredients.length >= " min " && this.ingredients.length <= " max}