Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get user ID during user creation in Meteor?

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: '[email protected]',
      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?

like image 827
Barry Michael Doyle Avatar asked Jan 21 '16 20:01

Barry Michael Doyle


1 Answers

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: '[email protected]',
  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}
        });
    }
});
like image 168
Brett McLain Avatar answered Oct 13 '22 11:10

Brett McLain