Counter or Reduce Best Practice

I need to create a dashboard for total transaction or sum transaction.

I create TransactionCollection

I have two ways:

  1. publish TransactionCollection.find({}, {fields: { total: 1}}), and subscribe it. afte that I use reduce to calculate all total in transactions.

  2. create CounterCollections
    this collections will increment every after TransactionCollection inserted
    with schema:

_id: string
amount: string

which one better way?

The answer depends in the requirements and also how large is this TransactionCollection, how many records it has, etc.

If this dashboard needs to be real-time it would be nice to use a publication (another option would be a method getting the data when the page loads) but if you are going to have thousands of transactions it would be a bad idea to send to the client thousands of transactions to display just the total.

So to take advantage of Meteor pub/sub to create the real-time experience it would be better to update another collection with your totals pre-calculated.

You can use collection hooks package to update your second collections when something changes in the transaction collection. Quave collections package also uses this same package to provide the ability to add hooks and also other stuff, like composers. But I think for your specific case above just the hooks package is enough.

So every time you have a change in the TransactionCollection you will fire a hook to update the CounterCollections and this second update will send this change to the dashboard in the client as you are going to have a publication population your dashboard.


Thank you very much, :blush: