Problem trying to add new field to Meteor.users collection

Hi.

I’m completely stuck at this. I searched for many hours here and at Google but can’t find an answer to my problem.

I’m trying to add a field for the logged user at the Meteor.users collection. It looks like it is working but the field is not there. :angry:

Method I’m using:

const handleUpdateApiKey = new ValidatedMethod({
  name: 'updateApiKey',
  validate: new SimpleSchema({
    apiKey: { type: String },
  }).validator(),
  run(apiKey) {
    if (!this.userId) {
      throw new Meteor.Error('unauthorized', 'You must be logged in to add an Api key!');
    }
    console.log('this.userId: ', this.userId);
    console.log('apiKey: ', apiKey);
    Meteor.users.upsert({ _id: 'w2mfAqGuh5Yk9GuaT' }, { $set: { ApiKey: '4421c7f6b2658358654bc58a80b8dccA' } }, function(error,result){
      console.log(error, result);
      if (error) {
        throw new Meteor.Error(500, error.message);
      } else {
        console.log('Update Successful');
      }
    // response
    });
  }
});

Called from component with:

    Meteor.call('updateApiKey', parameters, function () {
      console.log('Done!')
    })

I have plenty of console.log statements and it looks as everything is working:

I tried with Meteor.users.upsert and Meteor.users.update. Only difference is, in the first response is { numberAffected: 1 } with update is just "1"

The collection doesn’t changes

Any clue of what should be the problem, please?

This might have to do with the default subscription for users, which does not include your added field. When you create your own subscription for users, the merge box should add your field.

Try something like this

if(Meteor.isClient(){
 Tracker.autorun( function() {
  var userId = Meteor.userId(); // to force subscription when user login/logout
  Meteor.subscribe('ApiKey');
 });
}
if(Meteor.isServer) {
 Meteor.publish('ApiKey',function(){
  return this.userId ? Meteor.users.find(this.userId,{fields:{ApiKey:1}}) : [];
 });
}