首页 > 解决方案 > 使用 mongoose 通过字段的超集检索元素

问题描述

我的猫鼬模式Recipe看起来像这样:

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);

给定一个成分 ID 列表,我希望能够找到其成分列表是我正在搜索的列表子集的所有食谱。

我尝试了几件事无济于事,例如给出

  const ingredients = [
    ObjectId('614af0b845d87d639b1d337a'),
    ObjectId('614b12bebfbe29d357515c63'),
  ]

试图检索

Recipe.find({ ingredients: {$not: { $elemMatch: { $nin: ingredients } } }})

这不起作用,因为我没有考虑正确的字段ingredient,但我不知道应该在哪里。

标签: node.jsmongodbmongoose

解决方案


给定ingredients的是一个带有成分 ID 的数组,它需要是配方中成分数组的超集,这个查询有效:

   Recipe.find({ ingredients: { $not: { $elemMatch: { ingredient: { $nin: ingredients } } } } })

推荐阅读