[英]How to populate document nested in array of objects in Mongoose?
I want to populate the ingredientsList.我想填充成分列表。 Is it possible to get the array back with populated ingredients field?
是否可以使用填充的成分字段取回数组? How I can do it, if I want just one object out of ingredientsList with populated ingredient?
如果我只想要一个 object 和填充成分列表,我该怎么做?
Hope you can help:)希望你能帮忙:)
My Schema looks like this:我的架构如下所示:
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,
},
},
],
});
My Ingredient Model looks like this:我的成分 Model 看起来像这样:
export const IngredientSchema = new Schema({
name: {
type: String,
required: 'Enter a name',
},
created_date: {
type: Date,
default: Date.now,
},
amount: {
type: Number,
default: 1,
},
});
As the field, ingredientsList
, is an array of referenced documents from the Ingredient
collection - you can use model.populate()
as follows:作为字段,
ingredientsList
是来自Ingredient
集合的引用文档数组 - 您可以使用model.populate()
如下:
const recipes = await Recipe.find().populate('ingredientsList');
res.send({ data: orders });
This will return all Recipes
and also expand or populate the ingredientsList
for each.这将返回所有
Recipes
并扩展或填充每个食谱的ingredientsList
列表。
Let's say that you only wanted populate the name
field of each document in ingredientsList
- you do so as follow:假设您只想填充 componentsList 中每个文档的
name
ingredientsList
- 您可以按以下方式进行操作:
const recipes = await Recipe.find().populate('ingredientsList', 'name');
res.send({ data: orders });
This will return all Recipes
but only populate the name
field on ingredientsList
for each.这将返回所有
Recipes
,但仅填充每个ingredientsList
的name
字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.