I need to count all products in descending order and display them with spacebars. How would I do that?
Result should be:
book : 2
tv : 1
// My Collection
Records = new Mongo.Collection('records');
// My database
Records.insert({
name: "a", product: "book"
});
Records.insert({
name: "b", product: "tv"
});
Records.insert({
name: "c", product: "book"
});
// My Template Helper - This sorts for alphatical order
Template.foo.helpers({
'counterRecords': function(){
return Records.find({}, {sort: {product: 1}});
}});
// My Template
{{#each counterRecords}}
{{counterRecords}}: {{counterRecords.count}}
{{/each}}
Give this a try:
Template.myTemplate.helpers({
counterRecords: function() {
var records = Records.find().fetch();
return _.chain(records).pluck('product')
.countBy()
.map(function(v, k) {return {product: k, count: v};})
.sortBy('product')
.value();
}
});
That should produce an array like:
[{product: 'book', count: 2}, {product: 'tv', count: 1}]
And your template could look something like this:
{{#each counterRecords}}
{{product}}: {{count}}
{{/each}}