javascriptmeteormeteor-accounts

Meteor.user() is undefined in client-side controller


In the client-side of a METEORJS application, i have a controller that display some users.

I have a problem with Meteor.user() function, the error is : Meteor.user(...) is undefined.

Here is my code :

this.AdminUsersController = RouteController.extend({
template: "Admin",


yieldTemplates: {
    'AdminUsers': { to: 'AdminSubcontent'}

},

onBeforeAction: function() {
    var permissions = Meteor.user().profile.permissions;
    if (permissions && permissions.indexOf('Users') != -1)
        this.next();
    else this.redirect('/admin/dashboard');
},

action: function() {
    if(this.isReady()) { this.render(); } else { this.render("Admin"); this.render("loading", { to: "AdminSubcontent" });}
    /*ACTION_FUNCTION*/
},

isReady: function() {


    var subs = [
        Meteor.subscribe("users")
    ];
    var ready = true;
    _.each(subs, function(sub) {
        if(!sub.ready())
            ready = false;
    });
    return ready;
},

data: function() {

    var data = {
        params: this.params || {},
        users: Users.find({labo_id: Meteor.user().profile.labo_id}, {sort: {createdAt:-1}})
    };


    return data;
},

onAfterAction: function() {

}});

It's in the data function. I try to retrieve all users that are connected to the logged in user and got the same labo_id field...

I don't know why it give me that, because in the onBeforeAction function, i can access to Meteor.user(), and specially his profile...

Someone know what can i do to make it run ?

Thanks for your future answers :)


Solution

  • This is a timing issue. Meteor.user() does not necessarily return data, if it hasn't been loaded yet. Meteor.userId() however will return the _id of the user record (if they are logged in). If you can change your query to rely on that _id, then it can work.

    Depending on which router you are using, you can add a resolve: entry to ensure that the route waits for the user record to be loaded before activating it, and then your query will work.