简体   繁体   中英

Meteor.js: getting a sum of collection field

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?

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM