Meteor: Subscribe & Publish

Meteor

I've been investigating and learning Meteor this last year. I've decided to use my blog as a reference to the things I've been learning. Some of the things are super obvious, but mostly for my reference.

Below are the steps and organization I've used to setup subscribed and published data.

Structure

My app structure is as follows:

project_folder
 | client (client only code)
    | components (shared templates)
       | branding.html
       | navigation.html
       | toolbar.html
    | scripts (client specific scripts)
       | collections.js
    | styles (scss)
    | templates (layouts & structure)
       | layout
          | primary-layout.html
          | secondary-layout.html
       | section_folder (pages, posts, etc)
          | index.html
          | show.html
          | edit.html
          | _form.html
       | structure
          | header.html
          | content.html
          | footer.html
 | lib (shared between client & server)
    | collections.js
    | router.js
 | server (server only code)
    | collections.js
 | public
    | fonts
    | icons
    | images

1. Removing Autopublish

First thing I do is remove the autopublish package.

In console run the following command:

meteor remove autopublish  

That will remove the autopublish package and instantly make your data more secure.

2. Register Collections [lib]

This is how I register my collections.

  • Create a file and name it something like collections.js in the lib folder.
  • Register all your Mongo collections using the pattern in the code below.
[CollectionName] = new Mongo.Collection('[collectionName]');

3. Publish Collections [server]

This is how I publish my collections.

  • Create a file and name it something like collections.js in the server folder.
  • Publish all your collections using the pattern in the code below.
Meteor.publish('[collectionName]', function(){  
  return [CollectionName].find();
});

4. Subscribe Collections [client]

This is how I subscribe to my published collections.

  • Create a file and name it something like collections in the client folder or add it to an existing file where it makes sense like with the helpers code.
  • Subscribe to your collections using the pattern in the code below.
Meteor.subscribe('[collectionName]');  
  • Add another reference to the template helpers using similar code to below.
Template.[templateName].helpers({  
  [collectionName]: function(){
    return [CollectionName].find();
  }
});

Boom

I hope this has helped someone. I kept struggling to get it working. It finally worked when I moved the collection registration into the lib folder. That seemed to be my blocker. Where you create the files and place the code is a big deal.