Search code examples
meteoriron-routermeteor-accounts

Meteor: inserting a session variable value into a field upon user creation


This is branching from my previous question sent earlier Retrieve value from html 'value' attribute. I am now trying to insert a session variable value into field named 'userType' upon user creation. I have kept the insecure package so I can immediately perform Meteor.users.find().count(); in the console. So far, the users are not being created.

Am I inserting the session variable value the correct way, should this session value be inserted server side with Accounts.onCreateUser?

The client js

Template.joinForm.events({
'submit .form-join': function(e, t) {
    e.preventDefault();
    var firstName = t.find('#firstName').value,
    lastName = t.find('#email').value,
    email = t.find('#email').value,
    password = t.find('#password').value,
    username = firstName + '.' + lastName,
    profile = {
            name: firstName + ' ' + lastName,
            userType: selectedUserType
};

    Accounts.createUser({
        email: email,
        username: username,
        password: password,
        profile: profile
    }, function(error) {
        if (error) {
            alert(error);
        } else {
            Router.go('/');
        }
    });
}
});

I have made the 'userType' session variable global, please see as follows...

Template.authJoinType.events({
'click div.join-type-inner': function(e, tmpl) {
    userType = $(e.target).attr("value");
    Session.set('userType', userType);
    selectedUserType = Session.get('userType');
    console.log(selectedUserType);
}
});

Solution

  • createUser takes an options object with at most four fields: username, email, password, and profile. You are passing a fifth field which is being ignored. In order to transmit the userType data to the server you will need to add it to the profile object in the call to createUser.


    If it's important that userType exist on the root of the user document (instead of in the profile), you can modify it in the onCreateUser callback like this:

    client

    profile = {
      name: firstName + ' ' + lastName,
      userType: userType
    };
    

    server

    Accounts.onCreateUser(function(options, user) {
      if (options.profile) {
        if (options.profile.userType) {
          user.userType = options.profile.userType;
          delete options.profile.userType;
        }
        user.profile = options.profile;
      }
    
      return user;
    });
    
    Meteor.publish(null, function() {
      // automatically publish the userType for the connected user
      // no subscription is necessary
      return Meteor.users.find(this.userId, {fields: {userType: 1}});
    });