Jonathan Sutherland Jonathan Sutherland - 1 year ago 170
Javascript Question

Meteor - Publish just the count for a collection

Is it possible to publish just the count for a collection to the user? I want to display the total count on the homepage, but not pass all the data to the user. This is what I tried but it does not work:

Meteor.publish('task-count', function () {
return Tasks.find().count();

this.route('home', {
path: '/',
waitOn: function () {
return Meteor.subscribe('task-count');

When I try this I get an endless loading animation.

Answer Source

Meteor.publish functions should return cursors, but here you're returning directly a Number which is the total count of documents in your Tasks collection.

Counting documents in Meteor is a surprisingly more difficult task than it appears if you want to do it the proper way : using a solution both elegant and effective.

I encourage you using tmeasday:publish-counts which encapsulates a common pattern for publishing collection counts.

You can use it this way :

// server-side publish

// client-side use
    return Counts.get("tasks-count");

You'll get a client-side reactive count as well as a server-side reasonably performant implementation.

This problem is discussed in a (paid) bullet proof Meteor lesson which is a recommended reading :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download