Warning: this post is old and might not reflect the current state of the art

One of the key features of Meteor is provided by the data layer.

Since Meteor manages both the server and the client, I can explain the concept simply:

  • The server creates a publication
  • The client subscribes to that publication
  • Meteor keeps everything in sync


The server can precisely determine what each client will see. Each publication can be tailored upon parameters and user permissions.

Let’s do a simple Pub/Sub introduction on standard MongoDB collections.

Server publication

Here’s an example of a server code creating a publication for comments that have been approved:

//server-side code
Meteor.publish('comments', function() {
  return Comments.find({ approved: true });
});

Or we want to create a publication for comments made on a specific article:

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

The publish function is called every time a client subscribes.

Client subscription

On the client the code is very easy. For example, let’s subscribe to all comments:

Meteor.subscribe('comments');

Let’s instead subscribe to comments made on the current article:

var articleId = 23;
Meteor.subscribe('comments', articleId);

Once the subscribe method has been called, Meteor fills the client-side Minimongo (the MongoDB instance running on the client) with the data you chose to sent it.

Typically the client-side database only gets some records, the minimum amount needed to initialize and work. You don’t replicate the whole server-side Mongo collection content of course, but you request data as needed.

Autopublish

Meteor makes it very easy for us to start diving into a project without worrying at all about publications and subscriptions.

It does this by including the autopublish package in every new project. That that packages does is, it automatically creates a pub/sub for each collection we have defined, syncing all the data available from server to client.

When you’ll reach the phase when you need more control on the data available to each user or view, you’ll just remove the autopublish package and you’ll manually define what you need.