NodeJS 如何在下面的模型中通过数组中的ingredientId进行搜索?

oyjwcjzk  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(73)

我正在尝试根据items数组中的ingredientIds进行搜索
我正在尝试进行一个搜索,它将返回所有在ingredientId中包含ingredientId的食谱。items,我已经尝试过了

Recipe.find({
    "ingredients.items.ingredientId": ingredientId,
  });

但它返回一个空数组,这就是模型

const recipeSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  category: {
    type: String,
    required: false,
  },
  portions: {
    type: String,
    required: true,
  },
  ingredients: {
    items: [
      {
        ingredientId: {
          type: Schema.Types.ObjectId,
          ref: "Ingredients",
          required: false,
        },
        quantity: { type: Number, required: false },
      },
    ],
  },
  instructions: {
    type: String,
    required: true,
  },
  imageUrl: {
    type: String,
    required: false,
  },
});
rqmkfv5c

rqmkfv5c1#

我有这个问题,我建议尝试这个,你的代码看起来对我来说是正确的。

import { Types} from 'mongoose'

Recipe.find({
    "ingredients.items.ingredientId": new Types.ObjectId(ingredientId),
});

相关问题