Updating username in user collection?


#1

I have a form that the user can input to change their username. Upon submit, I want to update their username.

I initially tried this:

'submit .editProfileForm': function(event) {
      event.preventDefault();
      var newUsername = event.target.newUsernameInput.value;
      //update users username.
       Meteor.users.update(Meteor.userId, {
         $set: {
           username: newUsername
         }
  });
    }

But was getting a generic Access denied in the console. I then saw that using Accounts.setUsername() was recommended, so I tried the following:

'submit .editProfileForm': function(event) {
      event.preventDefault();
      var newUsername = event.target.newUsernameInput.value;
      //update users username.
      Accounts.setUsername(Meteor.userId(), newUsername)
    }

This instead gave me a TypeError:

TypeError: Accounts.setUsername is not a function

So what is the proper way to do this? I know the users Collection is a “special” Collection so i’m not sure if theres some other steps needed.


#2

You should write a Method and do it inside the method. Updating collections from the client in this way is not recommended in a production app, and so it is not possible, especially for security-related stuff like usernames.


#3

Yea, I remembered this from my experiences with Meteor before, but with the autopublish+insecure packages I figured it might by possible.

That said, even after creating the method, im not able to update the Collection using `Accounts.setUsername(Meteor.userId(), newUsername)`.

Instead, I get the following:

Exception while simulating the effect of invoking ‘users.updateUsername’ TypeError: Accounts.setUsername is not a function(…) TypeError: Accounts.setUsername is not a function

Is there something else that needs to be done to use the Accounts api?

EDIT: nvm, seems to be working fine, thanks.