Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor - Why should I use this.userId over Meteor.userId() whenever possible?

Judging from this comment by David Glasser in the GitHub issues:

this.userId is the primary API and Meteor.userId() is syntactic sugar for users new to JavaScript who might not understand the details of successfully using this yet

It seems like we should use this.userId whenever possible (such as inside a method function, where you can use both), and only use Meteor.userId() inside publish functions. If this assumption is correct, why?

(Referring to the relevant bits of the code would also be helpful, I can't seem to find it)

like image 796
dayuloli Avatar asked Sep 26 '15 17:09

dayuloli


1 Answers

Your question seems to conflate Meteor.userId() and Meteor.user(). The body of the question seems to be asking about the former while the subject line is asking about the latter. I'll try to address both.

  1. On the server, within a publish function, calling either Meteor.userId() or Meteor.user() will cause an error. Instead, use this.userId or Meteor.users.findOne(this.userId), respectively. However, note that the publish function is only called when a client subscribes. If you want the publication to change when the user record changes, you'll need to observe() the cursor returned by Meteor.users.find(this.userId) and take appropriate action when the record changes.
  2. On the server, while a method call is being processed, Meteor.userId() and Meteor.user() will correspond to the ID of the calling user and their record, respectively. However, be aware that calls to Meteor.user() will result in a DB query because they are essentially equivalent to Meteor.users.findOne(Meteor.userId()).

    Directly within a method call, you can also use this.userId instead of Meteor.userId(), but you are unlikely to see a significant performance difference. When the server receives the method call, it runs your method implementation with the user's ID (and some other info) stored in a particular slot on the fiber. Meteor.userId() just retrieves the ID from the slot on the current fiber. That should be fast.

    It's generally easier to refactor code that uses Meteor.userId() than this.userId because you can't use this.userId outside of the method body (e.g. this won't have a 'userId' property within a function you call from the method body) and you can't use this.userId on the client.

  3. On the client, Meteor.userId() and Meteor.user() will not throw errors and this.userId will not work. Calls to Meteor.user() are essentially equivalent to Meteor.users.findOne(Meteor.userId()), but since this corresponds to a mini-mongo DB query, performance probably won't be a concern. However, for security reasons the object returned by Meteor.user() may be incomplete (especially if the autopublish package is not installed).
like image 64
Dean Brettle Avatar answered Oct 04 '22 04:10

Dean Brettle