Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple subscription are returning same results even if match param is different #63

Open
mad-coder-365 opened this issue Apr 26, 2022 · 1 comment

Comments

@mad-coder-365
Copy link

I am trying to make this work for the past many hours but can't figure out what am I doing wrong.

I have a publish method

Meteor.publish("userEquipments", function (uid = null) {
  const userId = uid ?? this.userId;
  ReactiveAggregate(this, EquipmentsCollection, [
    { $match: { userId: { $eq: userId } } },
    {
      $lookup: {
        from: "items",
        localField: "itemId",
        foreignField: "_id",
        as: "items",
      },
    },
]);
});

On another page, I have 2 subscriber code

const myEquipments = useTracker(() => {
    if (!Meteor.userId()) {
      return [];
    }

    const handler = Meteor.subscribe("userEquipments", Meteor.userId());
    if (!handler.ready()) {
      return [];
    }

    return EquipmentsCollection.find().fetch();
  });

  const opponentEquipments = useTracker(() => {
    if (!opponent || !opponent._id) {
      return [];
    }

    const handler = Meteor.subscribe("userEquipments", opponent._id);
    if (!handler.ready()) {
      return [];
    }

    return EquipmentsCollection.find().fetch();
  });

Both of these subscriptions are returning the same results which are wrong as the match params have different IDs.

When I add a filter on the client-side, I get empty results.

 const handler = Meteor.subscribe("userEquipments", opponent._id);
    if (!handler.ready()) {
      return [];
    }

    return EquipmentsCollection.find({
      userId: opponent._id,
    }).fetch();

How can I call subscribe multiple times on the same page but with different match IDs?

@robfallows
Copy link
Owner

This is not an aggregation issue, but a fundamental result of the way publications work.

In effect a publication only runs once - which means that anything you set outside of the query will only ever be computed the first time the publication is run. In your code, that's: const userId = uid ?? this.userId;

The way to get the effect you want is to ensure the publication is re-subscribed to from the client - the original publication is stopped and the new one takes over.

The documentation for this behaviour is a little hard to find, but some information with possible solutions is here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants