I have a client side local collection named Cart which holds product objects. What I want to do is return to the template the sum of all the products and quantities in the collection. I do this as follows:
Template.layout.helpers({
cartTotal: () => {
if( !Cart.findOne({}) ) {
return 0;
}
else {
let productsCursor = Cart.find({});
let totalPrice = 0;
productsCursor.map((product) => {
let subtotal = product.qty*product.price;
totalPrice =+ subtotal;
console.log(totalPrice);
});
return totalPrice.toFixed(2);
}
}
});
Everything sums nicely when I’m adding the same product to the collection (increasing the product.qty by 1), but when I add another object to the Cart collection, it starts to sum only the quantities and price in this object.
If I inspect the Collection on the browser console, all the objects are there, but the result of the cartTotal method is not returning the correct value.
I’ve already tried to use the Mongo.Cursor#forEach() method, but the result is the same. How can I achieve what I’m trying to do??? What is wrong???