【问题标题】:Populating an array of arrays in Mongoose在 Mongoose 中填充数组
【发布时间】:2019-03-28 06:28:07
【问题描述】:

我正在尝试填充数组数组。架构如下所示:

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

【问题讨论】:

  • 你有什么错误吗?
  • 不,它只是没有填充它。它作为一个 ID 保存
  • meal 是查询、模型还是文档? (在meal.populate(...)的上下文中询问)

标签: javascript node.js database mongoose


【解决方案1】:

试试这个方法

meal.find({}).populate('ingredients.ingredient').exec(...)

【讨论】:

  • 谢谢。我试过这个,但它不起作用。我认为它实际上与我展示的示例相同。
【解决方案2】:

下面是你问题的解决方案。

成分架构文件:

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 格式:

【讨论】:

  • 感谢您抽出这么多时间,非常感谢!我认为你所做的与我需要的不同。我的膳食模式不是成分引用数组,而是对象数组,其中每个对象包含多个字段,包括成分引用。我添加了一些 cmets 以使这一点更清楚。再次感谢!
  • 在这种情况下,您有 3 个模式(膳食、成分附件和成分),对吧?
  • @Yaeger 我用 3 个模式更新了我的答案,现在我相信这会解决你的问题。
  • 非常感谢,但这仍然不是我想要的。正如您在我的示例中看到的,成分附件不是一个单独的模式。我刚刚提取了这个对象,所以我的Meal 架构会更清晰一些。看看我的编辑,我写下了我是如何“解决”它的。
猜你喜欢
  • 2019-07-28
  • 2019-01-31
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2016-01-19
  • 2021-02-23
相关资源
最近更新 更多