'Mongoose deep multi level population

i'm building e-commerce app with NodeJS and MongoDB. I have schema for product categories with subcategories, I need to populate on multi-level on subcategories. For Example i have parent category "Mens Clothing" with subcategory "T-shirts" with sub "Graphic T-shirts" and so on. So i need to populate every subcategory on every subcategory. Here is my Schema:

 {
    name: String,
    slug: {
      type: String,
      unique: true,
      required: true,
    },
    featuredPhoto: String,
    description: String,
    parent: {
      type: mongoose.Schema.Types.ObjectId,
      default: null,
      ref: "Categories",
    },
    subCategories: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: "Categories",
    }],

and here is my controller:

  const categories = await categoryModel
    .find({ parent: null })
    .select("name _id slug parent subCategories")
    .populate([
      {
        path: "subCategories",
        model: "Categories",
        select: "name slug _id subCategories",
        populate: {
          path: "subCategories",
          model: "Categories",
          select: "name slug _id subCategories",
        },
      },
    ]);

As you can see i have two nested populations, but if i have sub-categories in sub-sub categories it's not populated. I want to populate every subcategory no matter how many sub categories it's have. Here is screenshoot: enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source