Заполнение массива массивов в Mongoose - PullRequest
0 голосов
/ 24 октября 2018

Я пытаюсь заполнить массив массивов.Схема выглядит следующим образом:

const IngredientAttachment = {
    ingredient: { type: mongoose.Schema.Types.ObjectId, ref: Ingredient.modelName, required: true },
    // there's more fields here
};


const mealSchema = new Schema({
    ingredients: [[ IngredientAttachment ]] // array of array of attachments
    // there's more fields here
});

Пример незаполненного Meal документа выглядит следующим образом:

{
  "ingredients": [
    [{
        "_id": "5bcf9b3f2e33ad15f52bd831",
        "ingredient": "5bce60f074c12923c589db90"
      },
      {
        "_id": "5bcf9c94652b8f164f6a2566",
        "ingredient": "5bce85b76bb8812b2eb5322c"
      }
    ]
  ]
}

Я пытался использовать это:

meal = await meal
    .populate({
        path: 'ingredients',
        populate: {
            path: 'ingredient',
        }
    })

но это ничего не делает:)

Спасибо!

РЕДАКТИРОВАТЬ: На данный момент я "решил" это, введя поле options:

ingredients: [{
    options: [ IngredientAttachment ]
}]

ГдеМне нужна еда в виде массива ингредиентов, я просто преобразовываю ее так:

meal.ingredients = meal.ingredients.map(m => m.options);

Ответы [ 2 ]

0 голосов
/ 25 октября 2018

Ниже решения вашей проблемы.

Файл схемы ингредиента:

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));

Это вывод после выполнения:

mongoose meal populated

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

json formatted

0 голосов
/ 24 октября 2018

Попробуйте вот так

meal.find({}).populate('ingredients.ingredient').exec(...)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...