Accounts.onCreateUser adds extra attributes when creating new users, best practices?

I create a new user with Accounts.createUser () and it works fine if you do nothing. But I want to add some other fields to the new user that are not listed in the 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 added secretAttribute to my options object. Since this is not documented, it is just true that I am not adding my attribute to the user object.

So, I googled and realized 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 that, it does not save the 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 do I want from you guys?

  • I want to know why onCreateUser is losing the profile (before the fix above) in my case?
  • Is my approach a good practice?
  • Is there a better solution adding additional attributes to a user object when they are created?

ps: I think it’s obvious why I don’t want to save all additional fields under the profile;)

+8
meteor meteor-accounts
source share
3 answers

Well, that wasn't so difficult. Here it is in the documentation: "By default, the created user-defined function simply copies options.profile to the new user-defined document. Calling onCreateUser overrides the default hook." - Accounts.onCreateUser

+4
source share

Try the following:

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

The best I have found in this problem:

 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

0
source share

All Articles