Question

I have an app where I want to display a counter of elements I have in one of the collection. To do so I use a helper that I call in my HTML file {{nbPosts}}

UI.registerHelper('nbPosts', function () {
return Posts.find().count();
});

But to display it I need to subscribe to the whole Posts collection. It does not seem right to me, any suggestion to do that in a better way without sending the whole collection ?

Thanks,

Was it helpful?

Solution

It depends on whether you need this to update the data reactively (which I think is not the best idea), or not. If reactivity is not important you can just use a server method, so

Meteor.methods({
  'nbPosts': function () {
    return Posts.find().count();
  },
});

If you need reactivity you can implement a custom publish method, just like in this example. Just keep in mind that this will be a lot more expensive in terms of server usage, and so a much less efficient.

OTHER TIPS

The easiest way would be to have a collection that just keeps track of the number of posts, and update it whenever a post is inserted or removed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top