Its a bit tricky, you need a custom publish function and a virtual collection on the client side (userCount
)
This only publishes the count of the number of users online, and changes it as it changes using the Observer query.
This way you don't have to publish all the documents of the users who are online :) so as you have more users it wont slow down your client as much.
Server side code
Meteor.publish("userCount", function() {
var self = this;
var presences = Presences.find({online: true});
var count = presences.count();
var handle = presences.observe({
added: function() {
if(!handle) return;
count++;
self.changed('userCount', 'count', {count: count});
},
removed: function() {
count--;
self.changed('userCount', 'count', {count: count});
}
});
self.added('userCount', 'count', {count: count});
self.onStop(function() {
handle.stop();
});
this.ready();
});
Client side code
var userCount = new Meteor.Collection("userCount");
Meteor.subscribe("userCount");
HTML (example)
<template name="example">
{{userCount}}
</template>
Template Helper
Template.example.userCount = function() {
var count_doc = userCount.findOne({_id:'count'});
return (count_doc && count_doc.count) || 0;
}