Search code examples
meteoriron-router

"Cannot read property 'username' of undefined" in a Meteor Route?


The page still renders as it should, but this appears in my console log.

Exception in callback of async function: TypeError: Cannot read property 'username' of undefined at null. (http://localhost:3000/router.js?39194109cc7760190c519a386d66c807ba19230c:48:9) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at onRerun (http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:520:9) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at onRun (http://localhost:3000/packages/iron_router.js?a427868585af16bb88b7c9996b2449aebb8dbf51:505:11) at boundNext (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:424:31) at Meteor.bindEnvironment (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:983:22) at dispatch (http://localhost:3000/packages/iron_middleware-stack.js?0e0f6983a838a6516556b08e62894f89720e2c44:448:3)

Which points to the line indicated below:

var OnBeforeActions = {
  loginRequired: function() {
    if (!Meteor.userId()) {
      this.render('hello');
    } else {
      this.next();
    }
  }
};
Router.onBeforeAction(OnBeforeActions.loginRequired, {
  only: ['home']
});

Router.route('/', function() {
  // this.render('homepage');
  Router.go('/users/' + Meteor.userId());
});

Router.route('/users/:user_id', function() {
  this.render('home', {
    data: {
      username: Meteor.users.findOne({
        _id: this.params.user_id
      }).username, // THIS LINE HERE
    }
  });
});

The idea is to redirect the user to his page if he is already logged in - and it appears to work as it should, but why am I getting this?


Solution

  • When the browser loads initially there will not be any data available (all the collections will be empty - until they are downloaded. Thus the result of the query Meteor.users.findOne({_id: this.params.user_id}) will be undefined.

    This is the reason you can't read username out of undefined.

    Since the query will re-run/it is reactive you just need to take account when it is null and it will sort itself out. user.username is only read if user is not null:

    Router.route('/users/:user_id', function() {
      var user = Meteor.users.findOne({_id :this.params.user_id});
      this.render('home', {
        data: {
          username: user && user.username
        }
      });
    });