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

断了今生、忘了曾经 提交于 2019-12-21 03:58:40

问题


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: "username@liamg.com",
    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 ;)


回答1:


Well it wasn't so hard.. Here it stands in documentation: "The default create user function simply copies options.profile into the new user document. Calling onCreateUser overrides the default hook." - Accounts.onCreateUser




回答2:


Try this:

Accounts.onCreateUser((options, user) => (Object.assign({}, user, options)));



回答3:


The best thing I found to this issue is:

Accounts.onCreateUser(function(options, user) {
    // Use provided profile in options, or create an empty object
    user.profile = options.profile || {};

    // Assigns first and last names to the newly created user object
    user.profile.firstName = options.firstName;
    user.profile.lastName = options.lastName;

    // Returns the user object
    return user;`enter code here`
});

https://medium.com/all-about-meteorjs/extending-meteor-users-300a6cb8e17f



来源:https://stackoverflow.com/questions/30050159/accounts-oncreateuser-adding-extra-attributes-while-creating-new-users-good-pra

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