Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor subscribe to a count

Is there any way to subscribe to a count in meteor.

I want to publish Articles.find().count() rather than publish Articles.find(). Ideally this should assign the count to a reactive Session that would change when the count changes.

like image 667
Harry Avatar asked Feb 01 '13 23:02

Harry


2 Answers

I have following code to publish my counters

Meteor.publishCounter = (params) ->
  count = 0
  init = true
  id = Random.id()
  pub = params.handle
  collection = params.collection
  handle = collection.find(params.filter, params.options).observeChanges
    added: =>
      count++
      pub.changed(params.name, id, {count: count}) unless init
    removed: =>
      count--
      pub.changed(params.name, id, {count: count}) unless init
  init = false
  pub.added params.name, id, {count: count}
  pub.ready()
  pub.onStop -> handle.stop()

and I use it like this:

  Meteor.publish 'bikes-count', (params = {}) ->
    Meteor.publishCounter
      handle: this
      name: 'bikes-count'
      collection: Bikes
      filter: params

and finally on client:

Meteor.subscribe 'bikes-count'
BikesCount = new Meteor.collection 'bikes-count'

Template.counter.count = -> BikesCount.findOne().count
like image 154
erundook Avatar answered Oct 28 '22 03:10

erundook


The Meteor documentation actually shows a good example of how to do this with the updated observe API. I'm reposting it here but the original documentation is here: http://docs.meteor.com/#meteor_publish.

Meteor.publish("counts-by-room", function (roomId) {
  var self = this;
  var count = 0;
  var initializing = true;
  var handle = Messages.find({roomId: roomId}).observeChanges({
    added: function (id) {
      count++;
      if (!initializing)
        self.changed("counts", roomId, {count: count});
    },
    removed: function (id) {
      count--;
      self.changed("counts", roomId, {count: count});
    }
    // don't care about moved or changed
  });

  // Observe only returns after the initial added callbacks have
  // run.  Now return an initial value and mark the subscription
  // as ready.
  initializing = false;
  self.added("counts", roomId, {count: count});
  self.ready();

  // Stop observing the cursor when client unsubs.
  // Stopping a subscription automatically takes
  // care of sending the client any removed messages.
  self.onStop(function () {
    handle.stop();
  });
});

// client: declare collection to hold count object
Counts = new Meteor.Collection("counts");

// client: subscribe to the count for the current room
Meteor.autorun(function () {
  Meteor.subscribe("counts-by-room", Session.get("roomId"));
});

// client: use the new collection
console.log("Current room has " +
            Counts.findOne(Session.get("roomId")).count +
            " messages.");
like image 44
cmather Avatar answered Oct 28 '22 01:10

cmather