Search code examples
javascriptmeteormomentjsmeteor-blaze

Meteor js. How to sum records per month of the same collection


I have the collection of invoices, with the tax field, I must call the invoices for each month and calculate the total tax.

I have Momentjs add to meteor and uses blaze.

App invoices


Solution

  • You can search your collection for invoices created in a particular month like so:

    var start = new Date(year, month, day);
    var end = new Date(year, month, day);
    
    //Invoices with a 'date' field between the 'start' and 'end' dates
    var cursor = CollectionName.find({ date : { $gte : start, $lt: end });
    

    You can then find the total of the tax fields:

    var taxTotal = 0;
    var results = cursor.forEach(function(doc) {
      //Adds the tax field of each document to the total
      taxTotal += doc.tax;
    });
    

    More information on the forEach method of a cursor can be found here