title: How to group records by a field in Mongoose?
body: <p>I've got a MongoDB document which has records that looks like this:</p>
  
  <pre><code>[
    { _id: id, category_name: 'category1', parent_category: null },
    { _id: id, category_name: 'category2', parent_category: null },
    { _id: id, category_name: 'subcategory1', parent_category: id_parent_1 },
    { _id: id, category_name: 'subcategory2', parent_category: id_parent_1 },
    { _id: id, category_name: 'subcategory3', parent_category: id_parent_2 },
    { _id: id, category_name: 'subcategory4', parent_category: id_parent_2 }
  ]
  </code></pre>
  
  <p>As you can see, I'm storing categories with a <code>parent_category</code> of <code>null</code>, and subcategories have the parent category's ID. What I'm looking for is to group these into some kind of format like this:</p>
  
  <pre><code>[
    { category_name: 'category1', categories: [
         { category_name: 'subcategory1', _id: id },
         { category_name: 'subcategory2', _id: id }
      ]
    },
    { category_name: 'category2', categories: [
         { category_name: 'subcategory3', _id: id },
         { category_name: 'subcategory4', _id: id }
      ]
    }
  ]
  </code></pre>
  
  <p>So basically group the parent categories with an array with their child categories. I'm using Mongoose. I tried using the aggregation framework MongoDB provides but I can't get the desired result. :(</p>
  
  <p>I have access to modify the schema in any way that could be needed!</p>
  
  <p>Thanks in advance!</p>