Publishing Counts for objects in Meteor

时间:2019-03-17 22:42:35

标签: mongodb meteor meteor-publications

On my server side I have for various objects a publication which basically returns the count. Every different object has a different publication name like this:

Meteor.publish('object1Count', function(...

Meteor.publish('object2Count', function(...

Which are something like this:

Meteor.publish('object1Count', function(arg) {
var self = this;
var count = 0;
var initializing = true;

var query = arg?{arg:arg}:{};
var projection = !arg?{limit:1}:{};

var handle = Object1.find(query, projection).observeChanges({
  added: function (idx) {
    count++;
    if (!initializing)
      self.changed("totalcounts", 1, {count: count});  
  },
  removed: function (idx) {
    count--;
    self.changed("totalcounts", 1, {count: count});  
  }
});

initializing = false;

self.added("totalcounts", 1, {count: count});

self.ready();

self.onStop(function () {
  handle.stop();
});

}); 

But as you see inside each of these methods there will be this line

self.added("totalcounts", 1, {count: count}); 

In fact on the client side when I need to access the count of an Object I do like this:

template.subscribe('object1Count', template.reactiveEventId.get());
...
TotalCounts = (typeof TotalCounts==='undefined')?new Mongo.Collection("totalcounts"):TotalCounts;

It apparently works, but now that I read it twice I wonder why, the "totalcounts" collection looks like the same for all the objects, so if I switch between pages needing different totalcounts (for different objects), I guess that the client destroys the local collection totalcounts and creates a new one. Does this happen also server side?

So finally my question is: what is the best practice? The projects need the total counts for various reasons: pagination, charts, etc.. I want to create the total counts server side and just pass the minimum data for that. Should I create different "totalcounts" for every object? What's the efficient way of doing this?

Thanks

1 个答案:

答案 0 :(得分:3)

b

表示将self.added("totalcounts", 1, {count: count}); totalcounts的文档添加到集合名称_id,其余数据为1。 因为它们具有相同的_id,所以您不能进行超过1个订阅。 顺便说一句,当模板“卸载”时,它将自动停止订阅。