Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accounts.onCreateUser adding extra attributes while creating new users, good practices?

I'm creating new user with Accounts.createUser() and it works normally if you are not doing anything fancy. But I want to add some other fields to new user that are not listed on documentation. Here is my code:

var options = {
    username: "funnyUserNameHere",
    email: "[email protected]",
    password: "drowssap",
    profile: {
        name: "Real Name"
    },
    secretAttribute: "secretString"
};

var userId = Accounts.createUser(options);

In this example I have added secretAttribute to my options object. Because this is not documented it's just fair it's not adding my attribute under user object.

So I googled and figured out that something like this might work:

Accounts.onCreateUser(function(options, user) {
    if (options.secretAttribute)
        user.secretAttribute = options.secretAttribute;

    return user;
});

And yes! This works, but there is always BUTT.. *BUT.. After this one it's not saving profile anymore under the user object. However this makes it work:

Accounts.onCreateUser(function(options, user) {
    if (options.secretAttribute)
        user.secretAttribute = options.secretAttribute;

    if (options.profile)
        user.profile = options.profile;

    return user;
});

So what I want from you guys?

  1. I want to know why onCreateUser loses profile (before the fix above) in my case?
  2. Is my approach good practice?
  3. Is there better solution adding extra attributes for user object while creating them?

ps: I thinks it's obvious why I don't want to save all extra fields under profile ;)

like image 846
lehtu Avatar asked May 05 '15 10:05

lehtu


1 Answers

Try this:

Accounts.onCreateUser((options, user) => (Object.assign({}, user, options)));
like image 63
Teng Zhang Avatar answered Nov 16 '22 02:11

Teng Zhang