1

I have a collection of Messages on my mongodb.

I have created two publish functions:

Meteor.publish("messages", function (self, buddy) {
  check(self, String);
  check(buddy, String);
  return Messages.find({participants: {$all : [self, buddy] }});
});

and,

Meteor.publish("conversations", function(self){
    check(self, String);
    return Messages.find(   
        { participants: { $in : [self] } }, 
        { participants: { $elemMatch: { $ne: self } }, messages: { $slice: -1 }} 
    );
});

And I subscribe to both of these on the client:

Meteor.subscribe("conversations", user);
return Messages.find();

and,

Meteor.subscribe("messages", user, buddy);
return Messages.find();

The subscriptions are located in different templates. The problem is that when I return the data from the conversation subscription the data is the same as from the messages subscription. I see the same results in both subscriptions even though they have different queries...

How can I solve this issue?

Xon
  • 55
  • 1
  • 1
  • 5

1 Answers1

1

This is normal behavior, the same collection contains data for both subscriptions. You need to filter on the client as well.

This https://www.discovermeteor.com/blog/query-constructors/ outlines a pattern for handling this.

The basic idea is to have the query part as common code for both the server and the client so it is self consistent.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • But then the user will be able to see all the queries, and we never trust users... – Xon Sep 23 '15 at 02:39
  • the user is only getting what you are publishing, you are publishing to the user two queries of the messages. Both sets the user is allowed to see. Its just they are in the same collection. All you need to do is separate out the data using the same query on the client side as well. – Keith Nicholas Sep 23 '15 at 02:41
  • no worries, just remember, the basic idea is you program on the client as if you were talking to a real mongo db directly. All the publish and subscribe are doing is limiting what data ends up on the client. – Keith Nicholas Sep 23 '15 at 02:46
  • The hardest thing for me to understand is when I subscribe to a publication. For example in a template helper I use Meteor.subscribe.... does it mean that the subscription lasts only inside the template helper and I won't be able to get results out of it, right? – Xon Sep 23 '15 at 02:53
  • you have a Collection called Messages that is global on the client side. While a subscription is active, that subscription will fill Messages. Anything on the client side could see the data from that subscription. – Keith Nicholas Sep 23 '15 at 02:59
  • There is another version of subscribe that is template based, and will stop subscribing when the template disappears – Keith Nicholas Sep 23 '15 at 03:02