Using meteor user data without a ton of Meteor.user() && Meteor.user().team && Meteor.user().team.number


#1

When storing data on the Meteor.user() object and then accessing it in a template I find that I have a bunch of code that looks like:

Meteor.user() && Meteor.user().team && Meteor.user().team.number

Is there a way to functionalize this or make it shorter?


#2

Refactor it into an object. You still need to write the multiple checks, but you’ll only need to do it once. Example:


#3

How about this:

((Meteor.user() || {}).team || {}).number


#4

I have struggled with this for quite a while as well. In the end, I decided to use the underscore.deep mixin for underscore.js.

See https://atmospherejs.com/practicalmeteor/underscore-deep

For example,

_.deep(Meteor.user(), "profile.emails.0.address") will give you either the address or undefined. It will not throw an error like “cannot find property “profile” of undefined”.


#5

What would that even do? When there is not Meteor.user(), it tries to access the field “team” of an empty object?


#6

Create function:

function shorter (args,callback) {
  if (Meteor.user() && Meteor.user().team && Meteor.user().team.number) {
    return callback
  } else {
    return false
  };
}

then,

shorter(args, function (err, id) {
  // do something if Meteor.user() && Meteor.user().team && Meteor.user().team.number true
})

#7

This is the short notation of Meteor.user() && Meteor.user().team && Meteor.user().team.number

team of empty object will be undefined, so finally all this expression will be undefined if Meteor.user() is undefined. I do not know if it is what you asked about, but I am widely use it everywhere to shorten object checking…