[英]Meteor.js: getting a sum of collection field
我有一個收藏品:
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"
我在頁面上為每個用戶顯示了一個項目列表。 如何顯示當前用戶的價格字段總和?
您可以將模板幫助程序與幾個下划線功能結合使用:
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);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.