Reputation: 99
I am trying to do a publication where it returns the group that has the code attribute equal to users selectedGroup
.
Meteor.publish('selectedGroup', function () {
return Groups.findOne({
code: Meteor.users.findOne(this.userId).profile.selectedGroup
})
})
and the subscription looks like this
Meteor.subscribe('selectedGroup')
return {
group: Groups.find({}).fetch()
}
But what I get is an array of all the groups that the user belongs to, and not the group that the publication should be returning.
Even when I do findOne() it returns the first object and not the one that the publication should be returning.
Upvotes: 2
Views: 391
Reputation: 2246
First, you shouldn't use findOne
in your publication - publications should return a cursor; in this case you will be publishing a single-document cursor (as long as only a single document in Groups matches the query). Just use find
in the publication.
Second, when you're fetching the data on the client, you should make your query appropriately specific. Currently you're fetching all groups to which your client is subscribed (presumably you have other publications and subscriptions running.) See here for the Meteor Guide's advice. You'll want to do something like this in your container:
return {
group: Groups.findOne({
code: Meteor.users.findOne(this.userId).profile.selectedGroup
})
}
Finally, if your user's selectedGroup can change, you should be aware that the data that publications provide can change, but their queries can't. So if your user's selectedGroup changes, the publication won't reflect this - as its query won't change. See here. So you will want to use the reactive publish package to deal with this.
Upvotes: 1