Meteor userId 存在但用户未定义
Meteor userId is present but user is undefined
在渲染我的 React 组件时,我得到 Meteor.user()
null
。然后我尝试访问 Meteor.userId()
并将其作为登录用户的 ID 正确。还尝试通过 Meteor.users.findOne()
访问用户但未成功。
我的问题是,为什么用户对象是未定义的,尽管用户标识是可访问的?
我使用以下代码片段进行测试:
var uid = Meteor.userId();
console.log(uid); // printed the _id correctly
var usr = Meteor.user();
console.log(usr); // undefined
var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1); // undefined
Meteor.userId()
可在登录后立即使用。 Meteor.user()
要求通过 DDP 将对象交付给客户端,因此它不会立即可用。
默认情况下,profile
密钥已发布。由于您关闭了自动发布,因此您可能希望发布您自己的用户特定密钥集。
我通常有:
服务器:
Meteor.publish('me',function(){
if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
this.ready();
});
客户:
Meteor.subscribe('me');
您还可以发布有关其他用户的信息,但要共享的密钥列表通常要小得多。例如,您通常不想与登录用户共享其他用户的电子邮件地址。
Meteor.user()确实不能直接用,可以试试下面的方法:
Tracker.autorun(function(){
var uid = Meteor.userId();
console.log(uid); // printed the _id correctly
var usr = Meteor.user();
console.log(usr); // undefined
var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1);
});
这应该首先打印未定义,然后打印正确的用户。
在渲染我的 React 组件时,我得到 Meteor.user()
null
。然后我尝试访问 Meteor.userId()
并将其作为登录用户的 ID 正确。还尝试通过 Meteor.users.findOne()
访问用户但未成功。
我的问题是,为什么用户对象是未定义的,尽管用户标识是可访问的?
我使用以下代码片段进行测试:
var uid = Meteor.userId();
console.log(uid); // printed the _id correctly
var usr = Meteor.user();
console.log(usr); // undefined
var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1); // undefined
Meteor.userId()
可在登录后立即使用。 Meteor.user()
要求通过 DDP 将对象交付给客户端,因此它不会立即可用。
默认情况下,profile
密钥已发布。由于您关闭了自动发布,因此您可能希望发布您自己的用户特定密钥集。
我通常有:
服务器:
Meteor.publish('me',function(){
if ( this.userId ) return Meteor.users.find(this.userId,{ fields: { key1: 1, key2: 1 ...}});
this.ready();
});
客户:
Meteor.subscribe('me');
您还可以发布有关其他用户的信息,但要共享的密钥列表通常要小得多。例如,您通常不想与登录用户共享其他用户的电子邮件地址。
Meteor.user()确实不能直接用,可以试试下面的方法:
Tracker.autorun(function(){
var uid = Meteor.userId();
console.log(uid); // printed the _id correctly
var usr = Meteor.user();
console.log(usr); // undefined
var usr1 = Meteor.users.findOne({_id: uid});
console.log(usr1);
});
这应该首先打印未定义,然后打印正确的用户。