Find all groups that the current user belongs to

I’m trying to return all Groups that the current user is a part of. Each user has a groups field which is simply an array of id’s of the groups the user belongs to.

Here’s what my user schema looks like:

    {
      "_id": "rW36Ap9e8HAjDpodY",
      "createdAt": ISODate("2016-02-25T08:08:20.636Z"),
      "services": {
        "password": {
          "bcrypt": "$2a$10$X6eLlHhk/3uFJRiEZTN1i.wB3GaYJawwgAci1gybQJbI4df2PbNzd"
        },
        "resume": {
          "loginTokens": [ ]
        }
      },
      "username": "user",
      "groups": [
        "fEn62kk97BudX5RfT"
      ]
    }

My server method for returning the correct groups:

userGroups: function(){
    var currentUser = Meteor.users.findOne({_id: Meteor.userId()});
    return Groups.find({_id: { $in: currentUser.groups}});
}

Then the call to that method in my helper:

groups: function(){
    return Meteor.call('userGroups');
}

I’ve tried debugging this in the console but I’m just getting more confused. I can call var user = Meteor.users.find(_id: Meteor.userId()) and it correctly assigns the current user to the variable, but then when I call user.groups (which is the array of group id’s) it says it’s undefined. If I check the document in the meteor mongo command line interface, the current user has a groups field with group id’s in it.

I can’t for the life of me figure out what I’m doing wrong here.

You cannot just do return Meteor.call('userGroups'); in a helper. On the client you must use the callback to get the result, and usually with the help of a ReactiveVar to get that result reactively:

Template.myTemplate.onCreated(function() {
  this.groups = new ReactiveVar([]);
  Meteor.call('userGroups', (err,result) => {
    if (err) {
      // do something with err
    } else {
      this.groups.set(result); // Save result when it arrives
    }
  });
});

Template.myTemplate.helpers({
  groups() {
    return Template.instance().groups.get(); // Get result when it changes
  }
}

You will need to meteor add reactive-var to your project.

@robfallows thanks for the help. Although another developer pointed out that by doing this, I was actually rebuilding what’s already available with Meteor’s publish and subscribe methods. I also hadn’t made the custom groups field available to the client:

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

Again, thanks for exposing me to reactive variables.