Return multiple cursors in a single publication
Did you know that you can return multiple collection-Cursors in a single publication?
This is a very powerful feature you should use if you want one publication to publish the main and related data combined (e.g. posts and their comments).
Using two separate publications
Lets say you have a post and want to get all the comments which belong to that post.
You could do it as follows:
Meteor.publish('post', function(id) {<br />
return Posts.find({<br />
_id: id<br />
});<br />
});<br />
Meteor.publish('comments', function(postId) {<br />
return Comments.find({<br />
postId: postId<br />
});<br />
});<br />
Meteor.subscribe('post', '12345678');<br />
Meteor.subscribe('comments', '12345678');
This works fine, but can be optimized so that only one publication is used.
Let’s take a look how this works:
Publishing two cursors
Meteor.publish('post', function(id) {<br />
return [<br />
Posts.find(id),<br />
Comments.find({<br />
postId: id<br />
})<br />
];<br />
});<br />
Meteor.subscribe('post', '12345678');<br />
Now you’ll get the post and the comments which belong to the post with just one publication.
This is way you won’t have to remember that you need to subscribe to the post and the corresponding comments separately.
Here’s the Meteor documentation of that feature which describes the usage of returning multiple cursors in one publication.
Note: At the time of writing this blog post you could only publish two different collections in one publication.