Accounts.onCreateUser 在创建新用户时添加额外的属性,好的做法?

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

我正在使用 Accounts.createUser() 创建新用户,如果您不做任何花哨的事情,它会正常工作。但我想向文档中未列出的新用户添加一些其他字段。这是我的代码:

var options = {
    username: "funnyUserNameHere",
    email: "username@liamg.com",
    password: "drowssap",
    profile: {
        name: "Real Name"
    },
    secretAttribute: "secretString"
};

var userId = Accounts.createUser(options);

在此示例中,我已将 secretAttribute 添加到我的选项对象中。因为这没有记录,所以它没有在用户对象下添加我的属性是公平的。

所以我用谷歌搜索并发现类似这样的方法可能有效:

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

    return user;
});

是的!这行得通,但总是有 BUTT.. *BUT.. 在这之后它不再保存 profile 在用户对象下。然而,这使它起作用:

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

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

    return user;
});

那么我想从你们那里得到什么?

  1. 我想知道为什么 onCreateUser 在我的案例中丢失配置文件(在上述修复之前)?
  2. 我的方法是好的做法吗?
  3. 是否有更好的解决方案,可以在创建用户对象时为它们添加额外的属性?

ps:我想很明显为什么我不想在配置文件下保存所有额外的字段;)

嗯,没那么难。它在文档中的位置如下:"The default create user function simply copies options.profile into the new user document. Calling onCreateUser overrides the default hook." - Accounts.onCreateUser

试试这个:

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

关于这个问题我发现的最好的事情是:

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