Accounts.findUserByUsername(username) is undefined after the user account creation

I am having a problem with Account-password package. I am creating a new user on client side as follows

createNewUser(event) {
    event.preventDefault();
    console.log("create new user");
    username = ReactDOM.findDOMNode(this.refs.createUsernameInput).value.trim();
    password = ReactDOM.findDOMNode(this.refs.createPasswordInput).value.trim();
    repasswd = ReactDOM.findDOMNode(this.refs.createPasswordAgain).value.trim();
    if (password != repasswd) {
      alert("password values didn't match." + " <br/>" +
        "Please retry.");
    } else {
      //TODO: do this on server instead
      id = Accounts.createUser({
        username: username,
        password: password
      });
      console.log("looking for: " + username);
      user = Meteor.call('doesUserExist', username);
      console.log("user: " + user);
      //Roles.addUsersToRoles(id, "trial");

    }
  };

Corresponding server side method is as follows

import {Meteor} from 'meteor/meteor';

Meteor.methods({
  doesUserExist : function (username) {
    console.log("inside server method: doesUserExist");
    if (Accounts.findUserByUsername(username) != null) {
      return true;
    } else {
      return false;
    };
  },
});

Once the user is created, based on the server console logs, the “doesUserExist” method is called correctly on the server side. I am expecting the value of user to be either true or false on the client side. However, I am getting undefined.
what am I missing here?

Thanks
Sudheer

Your Meteor.call() needs a callback:

console.log("looking for: " + username);
user = Meteor.call('doesUserExist', username, (error, result) => {
  if (error) {
    // do something with the error
  } else {
    console.log("user: " + result);
  }
});

Or you can use async/await:

1 Like

that is because use is created after method call, so checking for it inside call will return undefined. what you can do is add Meteor.users.after.insert(function(userId, doc) function to return value

@robfallows @muphet: Thanks for the quick response. I will give it a try and let you guys know in a couple of days.

Cheers
Sudheer

I changed the meteor.method to following and it seems to work

async createUserAccount(username, password) {
    console.log("inside server method: createUserAccount");
    const result = await Accounts.createUser({
      username: username,
      password: password
    });

    const newUserId = await Accounts.findUserByUsername(username);
    Roles.addUsersToRoles(newUserId, "trial");
    
    return result;
  },

I can see that the role “trial” is added to the new user that I just created.

Thanks guys Appreciate your help.

Sudheer

1 Like