1

I am learning Meteor and I am wondering why my data is not reactive when I publish it as follows:

Meteor.publish("users", function (userId) {
    // teams the user is member of
    var teams = _.pluck(Teams.find({members:userId}).fetch(), '_id');
    // users from all those teams
    var userIds = _.union.apply(_,_.pluck(Teams.find({_id:{$in:teams}}).fetch(), 'members'));
    // user cursor
    return Meteor.users.find({_id:{$in:userIds}},{fields: {_id:1, profile: 1, emails:1}});
});

Obviously, this works though

Meteor.publish("users", function (userId) {
    return Meteor.users.find();
});

I suppose the additional steps is responsible for breaking the reactivity, but how can I fix that?

znat
  • 13,144
  • 17
  • 71
  • 106

1 Answers1

2

There is only reactivity on the cursor being returned by Meteor.publish()

So in your return function, Meteor is only observing the Meteor.users.find cursor. It is the line...

return Meteor.users.find({_id:{$in:userIds}},{fields: {_id:1, profile: 1, emails:1}});

The array userIds that is in this query will hold the same values unless the publication is run again.

The publication is run again when a new userId passes through to the publication. The Teams.find query is run and holds new values. But this query's result is held inside a variable - teams. The variable is non-reactive and therefore, the cursor that is returned from the publication does not think it should run again.

The very first time the publication is run, you will get results. But when it is run again, the cursor will not query the database.

I recommend watching Chris Mather's video on Observe in a Publish Function and reading up on reactive joins on the client.

meteorBuzz
  • 3,110
  • 5
  • 33
  • 60