I have a list that subscribes to posts
publication with a limit
.
Publication
Meteor.publish('posts', function(options) {
check(options, {
sort: Object,
limit: Number
});
var posts = Posts.find({}, options);
return posts;
});
within the list, I have items under each
list.html
{{#each posts}}
{{> postItem}}
{{/each}}
within each postItem
, I would like to count its comment number.
I believe the code for above would be
Template.postItem.helpers({
commentsCount: function () {
return Comments.find({postId: this._id }).count();
}
});
The problem with this is that I would have to publish all of comments inside posts
publication which would really be inefficient.
I would like to make a publication where I could subscribe to it within Template level for each postItems
and just return the resulting Counts
I tried tmeasday:publish-counts
but I did not figure out how to make it work in my case, or even if it would be used in this scenario.
Option 1: Keep track number of comment in the
Posts
collection itself.Each time new Comment inserted, update the counter:
This way you doesn't need to subscribe
Comments
just to get the count, which will involve multiple round trip to server.Option 2: Use
Meteor.methods
andMeteor.call
to return the number of comment for each Posts. Multiple round trip to server will occur.Option 3: Use aggregation to
$group
and count no of comment on server and map it back to Posts on client.Option 4: Reactive joins
I strongly recommend option #1 for performance and reactivity.