-1

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.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
  • Typo: you are filtering on `{ fields: { customfield: 1 }}` instead of `{fields:{ customfields: 1 }}` – Michel Floyd Sep 09 '16 at 01:24
  • Sorry, yes, there's a typo in the example – but that's not there in my actual working code, so sadly that's not the culprit. – Matt Keefe Sep 09 '16 at 11:32

2 Answers2

0

Since customfield1 is nested in customfields, did you try stuff.customfields.customfield1?

Adam
  • 33
  • 5
  • Yes, and in fact I can get the console to log an array (rather than undefined or an error) but it's an empty one. – Matt Keefe Sep 08 '16 at 21:14
0

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.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
  • Ah, perfect. It seems I had written working code in earlier in the process but I wasn't aware of the _ready()_ issue. I will address this. Many thanks! – Matt Keefe Sep 10 '16 at 10:30