Reputation: 74
I have a collection with items:
Object_id: "CoQayo8QmhEJduwtr"
category: "Computers"
createdAt: Sat May 23 2015 17:53:30 GMT-0400 (EDT)link: "https://www.apple.com/mac-pro/"
price: "4999.00"
title: "Mac Pro"
updatedAt: Sun May 24 2015 01:27:06 GMT-0400 (EDT)
userId: "yN36TFg742wZcyjQG"
I have a list of the items displayed on a page for each user. How can I display a sum of the price field for the current user?
Upvotes: 1
Views: 320
Reputation: 22696
You can use a template helper along with a combination of several underscore functions :
Template.user.helpers({
// declare a new helper on your user page template
priceSum: function(){
// fetch every items belonging to the currently displayed user
var userItems = Items.find({
userId: this._id
}).fetch();
// extract the price property in an array
var userItemsPrices = _.pluck(userItems, "price");
// compute the sum using a simple array reduction
return _.reduce(userItemsPrices, function(sum, price){
return sum + parseFloat(price);
}, 0);
}
});
Upvotes: 1