Update reactive var with server Method

I have a problem with updating some values in Meteor app on client-side. I’m trying to understand how ReactiveVar works.
When I use find() method on collection on client-side the site updates immediately each time I change something. I want to achieve the same effect using ReactiveVar and server-side Method. So the code below works correctly for me:

// Client
Template.body.onCreated(function appBodyOnCreated() {
  this.subscribe('activities');
}

Template.body.helpers({
  getCounter() {
    return Activities.find({
                       editorId: Meteor.userId(),
                       'referredObject.type': 'LIST'
                   }).count();
}
});

But when I try to achieve the same effect with server-side Method it doesn’t work correctly. Code below updates variable only once. If I want to get current value I need to refresh the page.

// Server
Meteor.methods({'activitiesCreateCount'(userId, objectType) {
    check(userId, String);
    check(objectType, String);
    return Activities.find({
        editorId: userId,
        'referredObject.type': objectType
    }).count();
} 
});
// Client
Template.body.onCreated(function appBodyOnCreated() {
  this.subscribe('activities');
  this.activitiesAmount = new ReactiveVar(false);
}
Template.body.helpers({
  getCounter() {
    var tempInstance = Template.instance();
    Meteor.call('activitiesCreateCount', Meteor.userId(), 'TODO', function(err, response) {
      tempInstance.activitiesAmount.set(response);
    });
    return Template.instance().activitiesAmount.get();
}
});

How I can improve my code if I want always have a current value of the variable (like in the first client-side only example)?

Meteor methods aren’t reactive, only subscriptions are. If you want reactive counts, you’ll have to either count them on the client (which means you have to subscribe to all the documents you want to count) Or use a package that lets you publish and subscribe to counts:

1 Like

Says you shouldn’t apply this on more than 100 documents. Won’t a basic subscription update find().count()?

Yes if you want to the documents on the client you don’t need publish-counts.

publish-counts is for when you want to display a count without having to publish/subscribe the actual documents. But although it doesn’t send as much data to the client, it still queries the database, that’s why they don’t recommend to use it for too big queries.

I’m confused by the idea that you could just find().count() which should return cursor which likely just has length property. One would think that having package that deals with this explicitly recommends against liberal use of counting mongo cursors.

There’s nothing wrong with find().count(). But for it to work, you need to have the documents you’re counting available, that’s why you might want publish-counts.

If you perform count I don’t think it would actually fetch the actual DB records. That readme must be outdated. @tmeasday