Return multiple cursors in a single publication

Philipp Muens
1 min readAug 20, 2015

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Philipp Muens
Philipp Muens

Written by Philipp Muens

👨‍💻 Maker — 👨‍🏫 Lifelong learner — Co-creator of the Serverless Framework — https://philippmuens.com

No responses yet

Write a response