如何在Mongoose中填充嵌套在对象数组中的文档?

3
我希望填充ingredientsList。 有可能获得填充后的ingredients字段的数组吗? 如果我只想要一个填充了ingredient的ingredientsList对象,该怎么做?
希望你能帮忙 :) 我的模式如下:
export const RecipeSchema = new Schema({
  name: {
    type: String,
    required: 'Enter a name',
  },
  ingredientsList: [
    {
      ingredient: {
        type: Schema.Types.ObjectId,
        ref: 'Ingredient',
      },
      value: {
        type: Number,
        default: 1,
      },
    },
  ],
});

我的配料模型如下:
export const IngredientSchema = new Schema({
  name: {
    type: String,
    required: 'Enter a name',
  },

  created_date: {
    type: Date,
    default: Date.now,
  },
  amount: {
    type: Number,
    default: 1,
  },
});
1个回答

3

作为字段,ingredientsList 是从 Ingredient 集合中引用文档的数组 - 您可以使用 model.populate() 方法如下:

const recipes = await Recipe.find().populate('ingredientsList');

res.send({ data: orders });

这将返回所有Recipes并扩展或填充每个ingredientsList
假设你只想填充ingredientsList中每个文档的name字段 - 请按如下方式执行:
const recipes = await Recipe.find().populate('ingredientsList', 'name');

res.send({ data: orders });

这将返回所有Recipes,但仅为每个ingredientsList字段填充name字段。 Mongoose文档关于关联查询的说明

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接