3

I'm very new to Meteor, so this question might sound awkward. I'm trying to display a list of all posts

Posts = new Meteor.Collection('posts');

and then in Meteor.publish('posts', ...)

return Posts.find();

and show a number of comments related to each of those posts. Comments are stored in a separate collection

Comments = new Meteor.Collection('comments')

I don't want users to download all comments from the database just to find out comments count for each of the posts - I'm not displaying them here. So

Meteor.publish('comments', function(){
    return Comments.find();
})

is not an option.

I know I could denormalize the data and store commentsCount in Post documents. But is there any other way to do this? I'd like it to be observable - or rather live updating, of course. I know how to do it when displaying a single post, but I don't know how to do it for the whole list.

tshepang
  • 12,111
  • 21
  • 91
  • 136

2 Answers2

1

did you know that you can add parameters to your publish function?

you could have something like

Meteor.publish('comments', function(post){
    return Comments.find({postId: post._id});
})

this way you get only the comments for one post at a time.

Hope this was what you were looking for

Micha Roon
  • 3,957
  • 2
  • 30
  • 48
  • Hi! Thanks - I know about that, but this doesn't solve my problem, unfortunately. This is good for displaying/counting comments on currently displayed **single** post but isn't useful if you're showing a list of all posts... – Radek Brzózka May 19 '13 at 01:56
  • you could change the parameter to be an array of posts and then selecting with Comments.find({postId:{$in: posts}}) – Micha Roon May 19 '13 at 08:15
0

If you're just looking for the number of comments I think you can simply use:

{{commentsCount}}

So an example would be something like:

<h1>Post Title</h1>
<p>{{commentsCount}} comments</p>

Make sure that is used within a post template though or else it won't know which comments it should be counting for.

Colton45
  • 280
  • 1
  • 3
  • 17