Frank6
Frank6

Reputation: 1203

Weird bug with Accounts.onCreatedUser

Here is a weird bug I am having. First here is my code

User = {};

User._defaults = {
  emails : [],
  enabled : true
}

User.defaults = function(){
  var defaults = _.clone(User._defaults);
  return _.extend(defaults,{
    createdAt : new Date()
  });
}

Accounts.onCreateUser(function(options, user){    
  console.log(User.defaults()); 
  // returns {emails: [ { address: '[email protected]', verified: true } ], enabled: true}

  _.defaults(user, User.defaults());

  user.emails.push(user.services.linkedin.emailAddress);

  return user;
});

As you can see, when I call User.defaults() it returns an object with the emails array filled with the email address of the previous new use.

But what is even weirder, is that when I do this :

Accounts.onCreateUser(function(options, user){
  console.log(User._defaults, User.defaults());

  user.enabled = true;
  user.emails = [];
  user.createdAt = new Date();
  // _.defaults(user, User.defaults());

  user.emails.push(user.services.linkedin.emailAddress);

  return user;
})

The logged User.defaults() actually return an object with the emails array empty.

Anyone has an idea what can cause this ??

Thanks !!

Upvotes: 0

Views: 31

Answers (1)

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

This would have to do with the Underscore clone function. If you read the docs.

Create a shallow-copied clone of the provided plain object. Any nested objects or arrays will be copied by reference, not duplicated.

The important part is the shallow copy. Your array is not an actual copy, it's just a reference. So you are always referring to the same array every time.

I would do the following.

User = {};
User.defaults = function(){
  return {
    emails : [],
    enabled : true,
    createdAt : new Date()
  }
}

Upvotes: 1

Related Questions