Publishing data

It's time to remove our training wheels and start publishing our data. If you remember I mentioned the autopublish package was autopublishing all our data automatically. We want to remove this package and manually expose our data.

Here we are only publishing the top 3 posts.\label

To do this we specify what data we'd like published from the server, and then subscribe to it on the client.

Let's start by removing the autopublish package:

meteor remove autopublish

Minimongo is now empty because the client hasn't subscribed to any published data.\label

With the autopublish package gone our app becomes empty. Our Teams.find() is searching Minimongo, not the server side Mongo, so it's returning nothing. Getting data into Minimongo takes two steps:

  1. Publish data from the server
  2. Subscribe to the published data on the client

Step 1: Meteor.publish()

To begin with we will just publish all of our teams. Maybe in future we will paginate it, where we only publish say 10 teams at a time. Here's how we publish all our teams:

server/publications.js

Meteor.publish('teams', function(){
  return Teams.find();
});

With the server part done we can now test this in the browser by opening the console and typing the following:

Meteor.subscribe('teams');

Subscribing is like opening the floodgate - the published data rushes in...\label

And if we limit the publication to one ...

server/publications

Meteor.publish('teams', function(){
  return Teams.find({}, {limit: 1});
});

... we see it update in the browser (after typing Meteor.subscribe('teams') in the browser console):

Only one team is now being published\label

We'll keep the limit off for now, so feel free to change it back to just Teams.find() in the publish function.

Step 2: Meteor.subscribe()

As we've just experienced, subscribing will allow for data to flow into Minimongo from Mongo. This allows us to now search Minimongo with our client side find() calls and return data.

So all we have to do is write the Meteor.subscribe('teams') code and it'll work. In terms of where ... well it doesn't really matter as long as it's done in the client (so in a 'client' folder or wrapped in if(Meteor.isClient)).

When we start creating routes we'll do it differently (as we want different data depending on the route). But for now let's just create a new file called "subscriptions.js" in the client folder:

client/subscriptions.js

Meteor.subscribe('teams');

And now we have our 3 teams back working again.