Search code examples
mongodbmeteoruser-accounts

Custom fields and global subscriptions for Meteor user accounts


I'm adding custom data to Meteor user accounts for the first time. I've been able to add custom fields without difficulty and I know they're there because I can see them in Mongol. I am publishing via a global subscription so how do I then go about reading data from individual fields? It seems the syntax is very different from that when using publish/subscribe methods.

So, I have user accounts like this (as seen in Mongol):

"_id": "#################",
  "profile": {
    "name": "Test User"
  },
  "customfields": {
    "customfield1": [
      "A","B","C"
    ]
  }
}

In server/main.js I have the following

Meteor.publish(null, function() {
  return Meteor.users.find(this.userId, {fields:{customfields:1}});
});

This seems to be publishing fine. But what code do I use to render the cursor as data? I've been using variations on code like this in client/main.js and having no success:

var stuff = Meteor.users.find(this.userId).fetch();
console.log(stuff.customfield1);

Any help appreciated.


Solution

  • MyCollection.find() returns a cursor whereas MyCollection.findOne() returns an object, i.e. a single mongodb document.

    A publication must return a cursor or array of cursors. You publication is fine.

    You are basically trying to make the customfields key of the user object visible on the client. (The profile key is automatically published by Meteor).

    On the client, where you are doing:

    var stuff = Meteor.users.find(this.userId).fetch();
    

    You can simply use:

    var stuff = Meteor.user();
    

    or

    var stuff = Meteor.users.findOne(Meteor.userId());
    

    Then stuff.customfields will contain what you're looking for.

    The second form is way too verbose for me unless you're looking for a different user than the logged in user.

    Note: this.userId on the client will not be the userId of the current user, it will be undefined. That only works on the server. That may actually be the root cause of your problem. In addition, your publications must be ready() for the data to be available. This isn't true immediately after login for example.