Can't add user attribute using Accounts.onCreateUser

送分小仙女□ 提交于 2019-12-19 10:16:05

问题


I tried to add an attribute 'permission' to all newly created users. But it somehow doesn't work. I use this code to add the attribute

 Accounts.onCreateUser(function(options, user) {
  user.permission = 'default';
  if (options.profile)
    user.profile = options.profile;
  return user;
});

But when I retrieve a user object on the client side I can't see the attribute

u = Meteor.users.findOne(Meteor.userId)
u.permission
>undefined

What am I doing wrong?


回答1:


You create it properly. The problem is that client does not see this value. Taken from documentation:

By default the server publishes username, emails, and profile

So you need to publish / subscribe for the additional fields.

Server:

Meteor.publish('userData', function() {
  if(!this.userId) return null;
  return Meteor.users.find(this.userId, {fields: {
    permission: 1,
  }});
});

Client:

Deps.autorun(function(){
  Meteor.subscribe('userData');
});



回答2:


Meteor.users.findOne(Meteor.userId) should be changed to Meteor.users.findOne(Meteor.userId()).

Also, I'm not sure what fields on the user object that actually are transmitted to the client. You might need to changeuser.permission = 'default' to options.profile.permission = 'default' so your Accounts.onCreateUser will look like this:

Accounts.onCreateUser(function(options, user) {
    if(!options.profile){
       options.profile = {}
    }
    options.profile.permission = 'default'
    if (options.profile)
        user.profile = options.profile;
    return user;
});


来源:https://stackoverflow.com/questions/16605549/cant-add-user-attribute-using-accounts-oncreateuser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!