5

I am creating default users on the server with a Meteor startup function. I want to create a user and also verify his/her email on startup (I'm assuming you can only do this after creating the account).

Here's what I have:

Meteor.startup(function() {
  // Creates default accounts if there no user accounts
  if(!Meteor.users.find().count()) {
    //  Set default account details here
    var barry = {
      username: 'barrydoyle18',
      password: '123456',
      email: 'myemail@gmail.com',
      profile: {
        firstName: 'Barry',
        lastName: 'Doyle'
      },
      roles: ['webmaster', 'admin']
    };

    //  Create default account details here
    Accounts.createUser(barry);

    Meteor.users.update(<user Id goes here>, {$set: {"emails.0.verified": true}});
  }
});

As I said, I assume the user has to be created first before setting the the verified flag as true (if this statement is false please show a solution to making the flag true in the creation of the user).

In order to set the email verified flag to be true I know I can update the user after creation using Meteor.users.update(userId, {$set: {"emails.0.verified": true}});.

My problem is, I don't know how to get the userID of my newly created user, how do I do that?

Brett McLain
  • 2,000
  • 2
  • 14
  • 32
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143

1 Answers1

7

You should be able to access the user id that is returned from the Accounts.createUser() function:

var userId = Accounts.createUser(barry);
Meteor.users.update(userId, {
    $set: { "emails.0.verified": true}
});

Alternatively you can access newly created users via the Accounts.onCreateUser() function:

var barry = {
  username: 'barrydoyle18',
  password: '123456',
  email: 'myemail@gmail.com',
  profile: {
    firstName: 'Barry',
    lastName: 'Doyle'
  },
  isDefault: true, //Add this field to notify the onCreateUser callback that this is default
  roles: ['webmaster', 'admin']
};

Accounts.onCreateUser(function(options, user) {
    if (user.isDefault) {
        Meteor.users.update(user._id, {
            $set: { "emails.0.verified": true}
        });
    }
});
Brett McLain
  • 2,000
  • 2
  • 14
  • 32
  • The alternative option runs but the verified flag is still false. Should I be running the `onCreateUser` function before or after the `createUsers` function? Currently I'm running it after. – Barry Michael Doyle Jan 21 '16 at 20:57
  • 1
    The second solution is simply registering a call back for when accounts are created. Verify that it is running as expected by putting a console.log() in there. The code within that callback should run whenever a new account is created, not just in this single instance. As to the first solution, I amended it to not include a callback. – Brett McLain Jan 21 '16 at 21:15
  • 1
    Your new first solution did the trick! Thank you for your time :) – Barry Michael Doyle Jan 21 '16 at 21:21