fetch categories and Destruct to subcategory with mongodb aggregation

Viewed 121

According to this topic CRUD Operations on MongoDB Tree Data Structure I created this mongodb schema

const categorySchema = new mongoose.Schema({
  name: String,
  slug: { type: String, index: true },
  parent: {
    type: mongoose.Schema.Types.ObjectId,
    default: null,
    ref: "Category",
  },
  ancestors: [
    {
      _id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Category",
        index: true,
      },
      name: String,
      slug: String,
    },
  ],
});

How can I query from my category collection with aggregation pipeline to destruct my object into this form

ancestors :{
  mainCategoryName:[ 
                {subcategory 1},
                {subcategory2},
                { subcategory 3: 
                    {child of subcategory 3}
                 }
  ]
}
0 Answers
Related