Fine-grained User Reactivity in Meteor

Dominus
Dominus
Dec 8, 2014 · 1 min read

Setting the fields when using collection.find and collection.findOne is very important. This is from the Meteor docs.

Note that when fields are specified, only changes to the included fields will trigger callbacks inobserve, observeChanges and invalidations in reactive computations using this cursor. Careful use of fields allows for more fine-grained reactivity for computations that don’t depend on an entire document.

One place where this isn’t obvious is Meteor.user().

Meteor.user()

is the same as

Meteor.users.findOne(Meteor.userId())

Meteor.user() returns the whole user object.

Template.test.helpers({
username: function() {
return Meteor.user().username;
}
});

The above works but it’s bad because anytime any attribute of Meteor.user() changes the template will re-run. The below example is a better way of doing it.

Template.test.helpers({
username: function() {
var user = Meteor.users.findOne(Meteor.userId(), {fields: {username:1}});
if (user) {
return user.username;
}
}
});

Now the template will only re-run if Meteor.user().username changes.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store