Staple
Staple

Reputation: 712

Group simple Meteor Collection by field

This question has been asked in different forms before but I have never found a simple concise answer.

I have a basic collection for use in my template:

Template.snackPage.helpers({

  snacks: function() {
    return Snacks.find({}, {sort: {day: 1}});
  }

});

Which returns something like this:

{
    {day: "04-05-2016", title: "Oranges"},
    {day: "04-05-2016", title: "Bananas"},
    {day: "07-05-2016", title: "Grapes"},
    {day: "07-05-2016", title: "Herrings"},
    {day: "09-05-2016", title: "Mint slices"},
}

I want to list it in my template by day heading like this:

Day: 04-05-2016
    - Oranges
    - Bananas

Day: 07-05-2016
    - Grapes
    - Herrings

Day: 09-05-2016
    - Mint slices

My question is how do I do this while maintaining reactivity and with least overhead/fuss :)

Upvotes: 0

Views: 43

Answers (1)

Orbit
Orbit

Reputation: 2385

Underscores _.groupBy might work for this. You could also look into using the Mongo aggregation pipleline: http://docs.mongodb.org/manual/core/aggregation-pipeline/

Heres a similar SO question: "group by" queries on meteor collection

Upvotes: 1

Related Questions