在铁路由器中设置属于用户的数据

Setting data that belongs to a User in iron router

Router.route('/settings', {
  name: 'settings',
  data: function() {
    return Settings.findOne({userId: Meteor.user()._id});
  }
});

它在浏览器中显示错误:

Uncaught TypeError: Cannot read property '_id' of undefined


关于如何获取登录用户的设置记录有什么建议吗?

Meteor 登录过程通常需要几毫秒才能准备好,同时 Meteor.user() 将 return undefined 并且您的路由 data 方法的第一次执行将失败.

您可以使用 Meteor.userId() 来避免这种情况发生,直到用户真正连接。

Router.route('/settings', {
  name: 'settings',
  data: function() {
    return Settings.findOne({
      userId: Meteor.userId()
    });
  }
});