brysgo
brysgo

Reputation: 848

This this.userId() often null when calling from inside a meteor method

I recently started trying out the auth branch of meteor and depending where I call my meteor method that calls this.userId(), it will return null or the user id that I need.

To be a little more specific, it works when my meteor method is called from a coffeescript class initialized inside of Meteor.startup, but not when that same method is called from inside Meteor.publish.

The meteor method is simple and probably not relevant, but just in case:

Meteor.methods(
  get_user_id: ->
    return @userId()
)

EDIT: It seems people were not able to reproduce my problem, here is a patch on the todo auth example that should demonstrate it.

    diff --git a/examples/todos/server/methods.js b/examples/todos/server/methods.js
    index e69de29..d4182a6 100644
    --- a/examples/todos/server/methods.js
    +++ b/examples/todos/server/methods.js
    @@ -0,0 +1,6 @@
    +Meteor.methods({
    +  get_user_id: function() {
    +    console.log(this.userId());
    +    return this.userId();
    +  }
    +});
    diff --git a/examples/todos/server/publish.js b/examples/todos/server/publish.js
    index 1552c5e..87cb29f 100644
    --- a/examples/todos/server/publish.js
    +++ b/examples/todos/server/publish.js
    @@ -16,6 +16,8 @@ Todos = new Meteor.Collection("todos");

     // Publish visible items for requested list_id.
     Meteor.publish('todos', function (list_id) {
    +  Meteor.call('get_user_id');
    +  //console.log(this.userId())
       return Todos.find({
         list_id: list_id,
         privateTo: {

thanks Eitan for the patch!

Upvotes: 3

Views: 2855

Answers (4)

Patrick Coffey
Patrick Coffey

Reputation: 1083

You should use Meteor.userId() to retrieve the current user's ID within Meteor.methods. :)

Upvotes: 3

loomi
loomi

Reputation: 3096

This might be stupid: But, are you logged in? (Sorry, this was my problem finally.)


So best might be to check first if logged in:

if (this.userId)
    console.log(this.userId)

Upvotes: 1

Tom Coleman
Tom Coleman

Reputation: 3037

It's working for me. Are you sure that you are getting the return value of the Meteor.call properly? Something like:

Meteor.call 'get_user_id', (error, result) -> console.log(result)

What happens if you add console.log(@userId()) in your method?

Upvotes: 0

Tamara Wijsman
Tamara Wijsman

Reputation: 12348

this.userId() is on its own not reactive as far as I am aware of, so if you want other things to react on it you will need to put it inside a Session variable. So, from Meteor.startup you do:

Session.set('userId', this.userId());

Then, where you need it you can use this instead:

Session.Get('userId');

That way, when it is missing and thus null it will be filled in later.

Upvotes: 0

Related Questions