Ниже решения вашей проблемы.
Файл схемы ингредиента:
const mongoose = require('mongoose');
const ingredient = new mongoose.Schema({
name: {
type: String,
required: true
}
});
module.exports = mongoose.model('Ingredient', ingredient);
Файл схемы вложения ингредиента:
const mongoose = require('mongoose');
const ingredientAttachment = new mongoose.Schema({
ingredient: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Ingredient',
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('IngredientAttachment', ingredientAttachment);
Файл схемы питания:
const mongoose = require('mongoose');
const mealSchema = new mongoose.Schema({
ingredients: {
type: [[
{
type: mongoose.Schema.Types.ObjectId,
ref: 'IngredientAttachment',
required: true
}
]]
},
type: {
type: String,
required: true
}
});
module.exports = mongoose.model('Meal', mealSchema);
Это код, который я использовал для тестов:
const ingredientA = new ingredientSchema({name: 'ingredientA'});
await ingredientA.save();
console.log(`ingredientA=${ingredientA}`);
const ingredientB = new ingredientSchema({name: 'ingredientB'});
await ingredientB.save();
console.log(`ingredientB=${ingredientB}`);
const ingredientC = new ingredientSchema({name: 'ingredientC'});
await ingredientC.save();
console.log(`ingredientC=${ingredientC}`);
const ingredientD = new ingredientSchema({name: 'ingredientD'});
await ingredientD.save();
console.log(`ingredientD=${ingredientD}`);
const ingredientAttachmentA = new ingredientAttachmentSchema({ingredient: ingredientA, description: 'descriptionA'});
await ingredientAttachmentA.save();
console.log(`ingredientAttachmentA=${ingredientAttachmentA}`);
const ingredientAttachmentB = new ingredientAttachmentSchema({ingredient: ingredientB, description: 'descriptionB'});
await ingredientAttachmentB.save();
console.log(`ingredientAttachmentB=${ingredientAttachmentB}`);
const ingredientAttachmentC = new ingredientAttachmentSchema({ingredient: ingredientC, description: 'descriptionC'});
await ingredientAttachmentC.save();
console.log(`ingredientAttachmentC=${ingredientAttachmentC}`);
const ingredientAttachmentD = new ingredientAttachmentSchema({ingredient: ingredientD, description: 'descriptionD'});
await ingredientAttachmentD.save();
console.log(`ingredientAttachmentD=${ingredientAttachmentD}`);
const meal = new mealSchema({
ingredients: [[ingredientAttachmentA, ingredientAttachmentB], [ingredientAttachmentC, ingredientAttachmentD]],
type: 'spicy'
});
await meal.save();
console.log(`meal=${meal}`);
const mealPopulated = await mealSchema.find({_id:meal._id}).populate({
path: 'ingredients',
model: 'IngredientAttachment',
populate: { path: 'ingredient',
model: 'Ingredient' }
}).exec();
console.log('------ mealPopulated ------');
console.log(JSON.stringify(mealPopulated, null, 0));
Это вывод после выполнения:

Заполнить в формате json:
