user3139545
user3139545

Reputation: 7374

Meteor nested publications

I have two collections A and B in Meteor. For A I have a publication where I filter out a range of documents in A. Now I want to create a publications for B where I publish all documents in B that have a field B.length matching A.length.

I have not been able to find any example where this is shown but I feel it must be a standard use case. How can this be done in Meteor?

Upvotes: 0

Views: 114

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

This is a common pattern for reywood:publish-composite

import { publishComposite } from 'meteor/reywood:publish-composite';

publishComposite('parentChild', {
    const query = ... // your filter
    find() {
        return A.find(query, { sort: { score: -1 }, limit: 10 });
    },
    children: [
        {
            find(a) {
                return B.find({length: a.length });
            }
        }
    ]
});

This is a quite different pattern than serverTransform as on the client you end up with two collections, A and B, as opposed to a synthetic single collection A that has some fields of of B. The latter is more like a SQL JOIN.

Upvotes: 1

mutdmour
mutdmour

Reputation: 543

Use serverTransform

Meteor.publishTransformed('pub', function() {
  const filter = {};
  return A.find(filter)
    .serverTransform({
      'B': function(doc) {
        return B.find({
          length: doc.length
        }); //this will feed directly into miniMongo as if it was a seperate publication
      }
    })
});

Upvotes: 0

Related Questions