Meteor Mongo.Cursor#map doesn't have the desired effect

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:


  cartTotal: () => {
    if( !Cart.findOne({}) ) {
      return 0;
    else {
      let productsCursor = Cart.find({});
      let totalPrice = 0; => {
        let subtotal = product.qty*product.price;
        totalPrice =+ subtotal;

      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???

not sure you can map a cursor, try

let productsCursor = Cart.find({}).fetch();

Yes, map is on the documentation:

I don’t know exactly why, but substituting

totalPrice =+ subtotal;
totalPrice = totalPrice + subtotal;

completely worked. It may be a bug on minimongo or on babel… I’m not sure.

totally missed that. shouldn’t it be

totalPrice += subtotal;
1 Like

Such a stupid mistake. Thanks a lot! :slight_smile:

Hi, first note that this condition is unreachable

if( !Cart.findOne({}) ) {
   return 0;

find() allways returns Cursor, so Cart.find() === true anyway
Better solution is

const cursor = Cart.find({});
if (!cursor.count()) {
  return 0;

return cursor.fetch().reduce((memo, {price, qty}) => (memo + price * qty), 0).toFixed(2);

The docs for findOne state:

… Returns undefined if no matching document is found.

Which is testable as shown.