Generate unique username based off firstname and lastname


Is there a way to generate a unique username for my user based of its first and last name?

I know how to save a custom username but I can’t figure out how to check if the username I generate is taken or not, in the case that two users have the same first and last name.

I have the following on the server.

Accounts.onCreateUser(function(options, user) {
    const profile = options.profile;

    user.username ='user.generateUsername', options.profile);

    user.profile = profile;
    return user;

and in my meteor methods.

    'user.generateUsername'(profile) {
        const { fname, lname } = profile;
        const username = `${fname}${lname}`;
        let user = Meteor.users.findOne({ username });
        // if user result comes back, append number and recheck.
        return user;

User is undefined when I execute which is because Meteor.users.findOne is async. Is there a way to make the accounts.onCreateUser method happen after my user.generateUsername method has completed.


Nvm solved it. I didn’t realized user being undefined was expected because no user was found for my check.

    'user.generateUsername'(profile) {
        const { fname, lname } = profile;
        let username = `${fname}${lname}`;
        let user = Meteor.users.findOne({ username });
        let number = 0;

        while(user) {
            username = `${fname}${lname}${number}`;
            user = Meteor.users.findOne({ username });

        return username;