Reputation: 2153
So I want to subscribe to a publish function which only returns one object of a collection.
Meteor.publish("singleobject", function(bar) {
return MyCollection.find({foo: bar});
});
This should give me the SINGLE one object of the collection "MyCollection" where the foo property is equal to "bar", right? (There is only one object where this is true ... so findOne() should also work). What it does instead is returning me ALL objects of my collection, even those where foo is NOT equal to bar.
It works perfectly with another collection where there are more than one object where foo: "bar" is true. I can't really see what I am doing wrong. Can I not subscribe to a publish function which returns only one object?
Anyone has any ideas on this?! :-)
best regards Patrick
Upvotes: 1
Views: 788
Reputation: 2153
So ... do NOT put
Meteor.subscribe()
inside of
Meteor.autorun()
or
Deps.autorun()
. Everything inside Meteor.autorun()/Deps.autorun() is ALWAYS executed, even if it's inside a template specific .js file. I was thinking every single one of these js files is only loaded when the according template is loaded, which of course is totally wrong. This is only for structuring your app properly.
So if you want to subscribe to a publish function depending on the template loaded, put the Meteor.subscribe into the router callback functions and subscribe there.
Works perfect for me now! :)
Upvotes: 0
Reputation: 19544
The code you've used:
Meteor.publish("singleobject", function(bar) {
return MyCollection.find({foo: bar});
});
doesn't return just one object, but every object that has foo
equal to bar
. If you want just one (and no matter which one), you should use findOne
instead:
Meteor.publish("singleobject", function(bar) {
return MyCollection.findOne({foo: bar});
});
If you see also objects that have foo !== bar
, it means that you fetch them elsewhere. There are two possible explanations:
autopublish
package still on.Take care of these two things and you should be fine.
For subscription, this is the usual pattern:
Deps.autorun(function(){
Meteor.subscribe('channel');
});
If you want the subscription to only work from time to time, there are few ways to achieve it.
The simplest one is to add a boolean argument to the subscription, and set it to true only if you want the channel to work. In the publish method you then simply return null
if the flag is false.
More clean way is to track all your subscription handles and call stop()
on those you don't want to use at this moment. It's nice, but hard to recommend in this version of Meteor as everything has to be done manually, which adds some not really necessary work.
Upvotes: 3