[solved] Reactive publish

Ok, I’ve spent a lot of time making this work with observechanges() but no success.

I have the following query:
`Meteor.publish(‘empresas_invalidas_inspetor’, function() {
if (Roles.userIsInRole(this.userId, ZW.Roles.Inspetor))
var inspetor = Inspetor.findOne({id_user: this.userId});
var ids = Meteor.users.find({ roles: {$eq: “empresa”, $ne: “validado”}}, {fields: {_id: 1}}).map(function(item){ return item._id; });

return Empresa.find({id_user: {$in: ids}, inspetores: {$elemMatch: {$or: [{“cidadao.documento.numero”: inspetor.cidadao.documento.numero}, {“documento_conselho.numero”: inspetor.documento_conselho.numero}]}}});
return null;

What I want is when and the user roles changes, it reruns the “user find map” statment and then the “empresa find” statement.

Any ideias on how can simply achieve this, and please if you can explain how it works, because even reading the observechanges docs I can’t understand exactly whats happening there.


Try this

Meteor.publish('empresas_invalidas_inspetor', function() {
  if (Roles.userIsInRole(this.userId, ZW.Roles.Inspetor)) {
    var inspetor = Inspetor.findOne({id_user: this.userId});
    var users = Meteor.users.find({roles: {$eq: "empresa", $ne: "validado"}}, {fields: {id: 1}}); 
    var userIds = _.pluck(users.fetch(), '_id');

    return Empresa.find({
      $and: [
        {id_user: {$in: userIds}},
        {$or: [
          {'cidadao.documento.numero': inspetor.cidadao.documento.numero},
          {'documento_conselho.numero': inspetor.documento_conselho.numero}
  return this.ready();

Publications are not inherently reactive. So, changing a user’s roles will not necessarily re-run the publication with new data. There are a couple of ways you can address this:

  1. Use the client to pass a “roles have changed” parameter to the publication to force a re-publish.
  2. Use peerlibrary:reactive-publish to enable server-side reactivity in the publish function.

You have a small (but important) typo in your code (id --> _id) - should be:

var ids = Meteor.users.find({roles: {$eq: "empresa", $ne: "validado"}}, {fields: {_id: 1}}).map(function(item) {
  return item._id;

Thank you for your time, but just adding the ready() method didn’t make the subscription reactive.
And I used the new query you gave me, but that doesn’t seem to have anything in special besides the _pluck method, that I believe to be a helper function of loadsh?.

Thanks for you time.

Thank you man! The package you recommended worked like a charm, this just works! Thanks!

1 Like