9

I have a collection with fields groupNumber and number:

groupNumber, number
=================
1, 1
1, 2
1, 3
1, 4
2, 1
2, 2
2, 3
2, 8
3, 4
3, 5
...

I can print the entire collection with

{{#each numbers}}
  <tr>
    <td>{{groupNumber}}</td>
    <td>{{number}}</td>
  </tr>
{{/each}}

but I need it to be links instead. So at the first page I need to see a list of the group numbers (1, 2, 3, ...) and when I've clicked one of the groups, I see the numbers belonging to this group.

I could easily achieve this if I had groupNumber and number split in two different collections and use iron-router to navigate between list of groups and list of numbers belonging to group. But how can I get this with the two fields in the same collection?

Stennie
  • 63,885
  • 14
  • 149
  • 175
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

1 Answers1

5

Why don't you "group" your groups manually?

At first get all your group numbers.

var allValues = YourCollection.find().fetch();
var uniqueGroups = _.union(_.pluck(allValues, 'groupNumber')) //outputs [1,2,3]

After that, simple route will do the job:

Router.route('/group/:groupNumber?', function () {
  this.render('your_template', {
    data: function () {
      if(this.params.hasOwnProperty('groupNumber')){
          return {
             groupNumber: this.params.groupNumber
          }
      } else {
          var allValues = YourCollection.find().fetch();
          var uniqueGroups = _.union(_.pluck(allValues, 'groupNumber'))
          return {
              groups: uniqueGroups
          }
      }  
    }
  });
});

Then in your_template check, if you have groupNumber, show all numbers by YourCollection.find({groupNumber: this.groupNumber})

if not, then just render this.groups:

{{#each groups}}
<a href="/group/{{this}}">{{this}}</a>
{{/each}}
ZuzEL
  • 12,768
  • 8
  • 47
  • 68
  • What if I have two more levels `group1`, `group2`, `group3`, and `group4`? – Jamgreen Jul 05 '15 at 10:00
  • You're really asking a UX paradigm instead of using routes. – AZ. Jul 07 '15 at 00:38
  • 1
    The same logic applies with > 1 level of nesting or even recursive nesting. The only thing that seems missing from @Zuzel's answer is sorting which you presumably want to do at each level. – Michel Floyd Jul 09 '15 at 21:20