Reputation: 17372
I want to get some information out of a collection - in this example the user collection; but could be anything:
var result = Users.findOne({ _id: Meteor.userId() }).profile.anything;
In some cases the information is missing. For example if the DB is empty, I would get the error Exception in template helper: TypeError: Cannot read property 'profile' of undefined
.
What would be the best way to prevent this if I'm using findOne
and get an undefined result?
I would do something like:
var temp = Users.findOne({ _id: Meteor.userId() });
if (temp)
var result = temp.profile.anything;
But that looks not very elegant.
Upvotes: 0
Views: 50
Reputation: 64342
I cover this in some detail in my post on guards. This isn't really an issue with meteor or even the find
operations - its just defensive programming in JavaScript. The generally accepted practice in cases where a guard may be needed is something like:
x && x.y && x.y.z
which covers the case where one or more of x
and y
are undefined.
You may run into situations where a long function is predicated on the existence of some piece of data. In those situations you may want to do something like:
user = Meteor.user();
if (!user) return;
...
// rest of function which assumes user is defined
Upvotes: 1