My mongoose schema for Recipe
looks like this:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const RecipeSchema = new Schema({
recipeName: {
type: String,
required: [true, "Please add a recipeName"],
maxlength: [99, "max 50 chars are allowed for the recipeName"],
},
image: {
type: String,
},
ingredients: [
{
quantity: {
type: Number,
required: true,
},
ingredient: {
type: Schema.ObjectId,
ref: "Ingredient",
},
},
],
description: [
{
type: String,
required: [true, "Please add a description"],
maxlength: [5000, "max 50 chars are allowed for the description"],
},
],
});
module.exports = mongoose.model("Recipe", RecipeSchema);
Given a list of ingredients' ids, I want to be able to find all the recipes whose ingredients list is a subset of the list I am searching by.
I tried a couple of things to no avail, like for instance given
const ingredients = [
ObjectId('614af0b845d87d639b1d337a'),
ObjectId('614b12bebfbe29d357515c63'),
]
trying to retrieve by
Recipe.find({ ingredients: {$not: { $elemMatch: { $nin: ingredients } } }})
This doesn't work because I am not taking into account the right field ingredient
, but I do not know where that should be.
CodePudding user response:
Given ingredients
is an array with ingredients ids, which needs to be a superset of the ingredients array in the recipe, this query works:
Recipe.find({ ingredients: { $not: { $elemMatch: { ingredient: { $nin: ingredients } } } } })