tunguska-reactive-aggregate
tunguska-reactive-aggregate copied to clipboard
Multiple subscription are returning same results even if match param is different
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?
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.