Migration from populate() to aggregate()

Hi all!

My task is to change a query from populate() into aggregation pipeline.
The populate() work fine but we need to use aggregate.

Problem with the aggregation here:

menu return only menuItems and logo , and the logo is empty .

const pageDoc = await this.pagesModel.findById(pageId).populate({
  path: 'workspace',
  populate: [
    {
      path: 'pages',
      select: 'name slug published',
    },
    {
      path: 'subscription',
    },
    {
      path: 'menu',
      populate: [
        {
          path: 'logo',
        },
        {
          path: 'menuItems',
          populate: [
            {
              path: 'page',
              select: '_id name slug',
            },
          ],
        },
      ],
    },
    {
      path: 'icon',
    },
  ],
});

const pageDocAggree = await this.pagesModel.aggregate([
  {
    $match: {
      _id: new mongoose.Types.ObjectId(pageId),
    },
  },
  {
    $lookup: {
      from: 'Workspace',
      localField: 'workspace',
      foreignField: '_id',
      as: 'workspace',
    },
  },
  {
    $unwind: '$workspace',
  },
  {
    $lookup: {
      from: 'Page',
      localField: 'workspace.pages',
      foreignField: '_id',
      as: 'workspace.pages',
      pipeline: [
        {
          $project: {
            _id: 1,
            name: 1,
            slug: 1,
          },
        },
      ],
    },
  },
  {
    $lookup: {
      from: 'Subscription',
      localField: 'workspace.subscription',
      foreignField: '_id',
      as: 'workspace.subscription',
    },
  },
  {
    $lookup: {
      from: 'Menu',
      localField: 'workspace.menu',
      foreignField: '_id',
      as: 'workspace.menu',
    },
  },
  {
    $lookup: {
      from: 'MenuItem',
      localField: 'workspace.menu.menuItems',
      foreignField: '_id',
      as: 'workspace.menu.menuItems',
    },
  },
  {
    $lookup: {
      from: 'Files',
      localField: 'workspace.menu.logo',
      foreignField: '_id',
      as: 'workspace.menu.logo',
    },
  },
]);```

Hello @Mahady_Manana, Welcome to the MongoDB community forum,

Out of the question, It looks really poor schema design, I would suggest you improve your schema by reducing the lookup, by embedding the reference details in the main document instead of just a reference ID.

Refer to the detailed documentation with data modeling resources:

I love this blog “6 Rules of Thumb for MongoDB Schema Design”, and I would recommend you to read this,

1 Like

thanks for your advice, appreciate it :pray: