Adding attributes to the user-Object when creating a new user
This Blog post was updated due to security improvements mentioned by Dominik Ferber in the comments below.
Today I wanted to add custom fields to a users-Account when the user gets created.
I’ve done this several times before, but this time I thought I’d dive deeper into the documentation to see if there’s something more beautiful than my naive approach I used several times before.
The first approach one may consider would be to insert the user, fetch him from the database and update the fetched user-Document right away:
NOTE: NEVER EVER DO THIS AS THE PASSWORD IS SENT OVER THE WIRE IN PLAIN TEXT!
// Runs in both environments (server and client)<br />
Meteor.methods({<br />
addUser: function(user) {<br />
var newUser;</p>
<p> newUser = Accounts.createUser({<br />
email: user.email,<br />
password: user.password<br />
});</p>
<p> Meteor.users.update({<br />
_id: newUsers<br />
}, {<br />
$set: {<br />
firstName: user.firstName,<br />
lastName: user.lastName,<br />
isAdmin: false<br />
}<br />
});<br />
}<br />
});<br />
That will work but it’s not the ideal solution. What if the Meteor.users.update function throws an Error? Then the user will be created but not updated as needed. A way better solution is to use the Accounts.onCreateUser() API.
// user.js<br />
// This should be in the clients directory<br />
Accounts.createUser({<br />
email: user.email,<br />
password: user.password,<br />
firstName: user.firstName,<br />
lastName: user.lastName<br />
});</p>
<p>// utils.js<br />
// This should be in the server directory<br />
Accounts.onCreateUser(function(options, user) {<br />
user.firstName = options.firstName;<br />
user.lastName = options.lastName;<br />
user.isAdmin = false;<br />
return user;<br />
});<br />
This way the onCreateUser functionality gets called whenever a new user is created and all your custom attributes will be stored accordingly (in a transactional way).
I hope this helps you when dealing with such a situation!