node.js - 使用 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
,但我不知道应该在哪里。
解决方案
给定ingredients
的是一个带有成分 ID 的数组,它需要是配方中成分数组的超集,这个查询有效:
Recipe.find({ ingredients: { $not: { $elemMatch: { ingredient: { $nin: ingredients } } } } })
推荐阅读
- android - 从 launchWhenStarted 调用多个视图模型方法不起作用
- python - 如何在 django-rest-framework 中使用 session_key
- firebase - 如何在 Flutter 项目中预览链接
- python - 使用python查找变量之间的相关性
- linq - 匹配 sql 时,Linq 左外连接不起作用
- visual-studio-code - 为 C++ 设置 Visual Studio 代码,但无法编译
- flutter - 扩展时如何使扩展磁贴标题的字体更大?扑
- c - 释放内存导致分段错误 11
- python - 如何正确使用列表中的类型
- python - python在图中查找集群成员