Warz
Warz

Reputation: 7776

Confused about Publish/Subscribe and returning results

I am using meteor and i am a bit confused about the relationship between publishing/subscribing to documents and querying/returning collections to a client using the handlebars #each items helper.

I understand that by publishing and subscribing to certain documents, i get the reactive updating on the client side browser when things change.

I find my self writing very complex (role oriented) publish functions and writing the equivalent to return items to the client. For example,

Meteor.publish("directory", function () {
    var user = Meteor.users.findOne({_id:this.userId});
    //role and logic left out on purpose
    return Meteor.users.find({}, {fields:{emails:1, profile:1}});
});

and the subscribe

if (Meteor.userId() != null) {
    Meteor.subscribe("directory");
}

Template is called show people and the helper 'users'

 Template.show_people.users = function () {
     users = Meteor.users.find({}).fetch();
     return users;
 };

My question is, are things supposed to be done this way?. Do we return our list helpers the same query we used for publish?

Upvotes: 1

Views: 449

Answers (1)

travellingprog
travellingprog

Reputation: 1189

You can give a query cursor to the #each Handlebars function. In fact, it's recommended. In this manner, there will be a smart update of the DOM: when a document is added to the Cursor, Handlebars will only create new DOM nodes for that document, and not recreate the DOM nodes for the documents that were already present. This is not the case when you provide an array.

So that third piece of code can just be:

Template.show_people.users = function () {
     return Meteor.users.find({});
};

Note also that a collection.find() done client-side will only look in the documents inside your miniMongo storage... you're not doing a search through the entire server database, but only through the documents that the server has published to you.

So that complex, role-oriented logic is only necessary inside your Meteor.publish() function.

Upvotes: 1

Related Questions