Reputation: 990
If I create a table in a Template, is there a way to add a row of "reactive totals" at the bottom of the table using Meteor? Or do I have to write the code to sum the columns, the same way I would in ordinary JavaScript?
For example, given the table...
State Sales
NY 1234
FL 670
TX 2306
Total 4210
Can I use some reactive technique to calculate and keep the Total cell showing 4210
up-to-date as other cells change?
Upvotes: 1
Views: 669
Reputation: 69
I had the same issue, and have found the following solution for both columns and rows of a table
In Meteor, how can i do a sum of some computed fields in a table?
Upvotes: 0
Reputation: 8345
I've created the package peppelg:mongo-sum. With it, MyCollection.find().sum('field')
will return the sum of all the values in the field 'field'
.
Upvotes: 0
Reputation: 1538
Another way to do this is to use MongoDB $sum aggregator
Taking Erik Johnson's example, you need to do this:
// HTML
<div id="allSales">
<h2><span>Total sales: </span>{{allSales}}</h2>
</div>
// JS
Template.templatename.helpers({
allSales: function() {
var allSales = allStates.aggregate( [ { $group: { _id: null, total: { $sum: "$sales" } } } ]);
return allSales.total;
},
});
Upvotes: 2
Reputation: 55
This is how I've done it - I'm sure there's probably an easier way, but I'm still a beginner at Meteor:
// HTML
<div id="allSales">
<h2><span>Total sales: </span>{{allSales}}</h2>
</div>
// JS
Template.templatename.helpers({
allSales: function() {
var allStates = Statescollection.find();
var mappedItems = allStates.map((function(allStates) {return allStates.sales;}));
var allSales = _.reduce(mappedItems, function(memo, num){ return memo + num; }, 0);
return allSales;
},
});
Upvotes: 0