Dileet
Dileet

Reputation: 2074

Meteor publications and subscription

I'm trying to learn Meteor, and currently trying to wrap my head around publications and subscriptions. I'm following the discover meteor book and one main point just doesn't make sense to me and was hoping some explanations in simple terms can be shared.

So a publication is what "fetches" the data from the mongo database to store within Meteor:

Meteor.publish('posts', function() {
   return Posts.find(); 
});

Then on the client side I subscribe to the publication. Woopy

Meteor.subscribe('posts');

What doesn't make sense is the Template Helpers. Originally Discover Meteor tells you to create an array of static posts that iterate through each post using a template helper. Well now that I'm turning things dynamically my template helper becomes:

Template.postsList.helpers({
    posts: function () {
        return Posts.find();
    }
});

What's the point of running the Posts.find() on both the server and client template helper?

Upvotes: 3

Views: 422

Answers (2)

Tomas Hromnik
Tomas Hromnik

Reputation: 2200

Posts in publishing are server side collection. Posts in helpers are client-side collection which contains all published Posts. If you have thousands of posts you usually don't want to publish all Posts because it will take a few seconds to download the data.

You should publish just the data you need.

Meteor.publish('posts', function(limit) {
   return Posts.find({}, { limit: limit}); 
});

When you call this subscribe function, client-side collection Posts will contain just 100 posts.

var limit = 100;
Meteor.subscribe('posts', limit);

Upvotes: 2

boulaycote
boulaycote

Reputation: 602

In publications, you can setup exactly which Posts you want to store within the Posts collection on the client.

In your publish method, you could only return posts which contain the letter 'A'.

A typical use case is selecting objects which belongs to a user or a set of users.

Upvotes: 0

Related Questions