Reactive Count in Meteor

Posted on Jun 26, 2017

Reactive Count in Meteor

Whenever we talk about reactive count inside pagination in Meteor, then we face many issues like:

  • Memory Consumption.
  • CPU Consumption.

However, if we do some research then we can find some packages like publish-counts or we can manually observe the changes in a collection.

But after reading this blog you will not need to use any such package or observe changes while paginating or listing data to get the reactive count.

So the alternative to the above is Client Collection. Below is the implementation of client collection inside publish method:

// On server

Meteor.publish('pagination', function (data) {

    const count = Collection.find({}).count(); // Calculating count

    this.added('count', this.userId, { count: count }); //Inserting count to client collection

    return Collection.find({});

});

 

// On client

const Count  = new Mongo.Collection('count');

Count.findOne({_id: Meteor.userId});   //Fetching count 


Whenever there is any change inside collection(Collection) then the Meteor.publish will be called automatically by meteor and at the same time, the client collection will also get updated.

 

In this way, we get a reactive count with following advantages:

  • No extra memory consumption.
  • No extra CPU consumption.
  • It will not be affected by a large number of data(millions or more).