cala
cala

Reputation: 1421

2 publications inside a Meteor collection good practice

is it good or bad practice to publish 2 find querys inside the one Meteor.isServer function inside my collection?

I have this code: deals.js / collection

Meteor.publish('deals', function () {
    return Deals.find({ userId: this.userId });
  });

And I'd like to add another publication like so:

if (Meteor.isServer) {
Meteor.publish('deals', function () {
    return Deals.find({ userId: this.userId });
  });
Meteor.publish('deals', function () {
    return Deals.find({ category: 'technology });
  });
}

The reason for the 2nd publication is too enable a category component where only that category of results are displayed.

So now I can subscribe to this inside my component createContainer. Thanks!

Upvotes: 1

Views: 39

Answers (1)

ghybs
ghybs

Reputation: 53205

There is nothing wrong in itself having more than 1 publication from the same Collection.

However, in your case, I am not sure using the same 'deals' identifier for the Meteor publication is a good idea.

If your publications serve different purposes (typically they are used at different times / in different components), then simply use different names / identifiers.

But if I understand correctly, you actually want to use them in the same component, so that it receives Deals documents that are either from the current user or from a given category? In that case, simply use a MongoDB query selector with $or:

Meteor.publish('deals', function () {
    return Deals.find({
        $or: [{
            userId: this.userId
        }, {
            category: 'technology'
        }]
    });
}

Or even return an array of cursors:

Meteor.publish('deals', function () {
    return [
        Deals.find({ userId: this.userId }),
        Deals.find({ category: 'technology' })
    ];
}

(note that this also enables you to publish documents from different Collections in a single publication!)

Upvotes: 2

Related Questions