Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add user attribute using Accounts.onCreateUser

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?

like image 897
user2393256 Avatar asked Feb 11 '26 12:02

user2393256


2 Answers

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');
});
like image 152
Hubert OG Avatar answered Feb 13 '26 16:02

Hubert OG


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;
});
like image 41
Martin Avatar answered Feb 13 '26 17:02

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!