bp123
bp123

Reputation: 3417

How to access server aggregate on the client side within meteor

Bit of a noob question. I'm using meteor-native-mongo on the server to access the aggregate function in MongoDB, however, I'm not sure how I return and access the results on the client side. In the past subscribing and then accessing the collections on the client was pretty straightforward using the collection.find({}) function, however, I don't understand how to do it with the aggregate function. Can someone please explain.

Meteor.publish('companies', function(limit) {

  db.collection('companies').aggregate([{ $group: { _id: { location: "$google_maps.geometry_location" }, companies: { $addToSet: { name: "$company_name" } }, count: { $sum: 1} } }, { $match: { count: { $gt: 1 } } }]).toArray((err, result) => {
      console.log(result);
      return result;
  });

});

Upvotes: 2

Views: 746

Answers (1)

DoctorPangloss
DoctorPangloss

Reputation: 3073

Use this.added, this.changed, this.removed from https://docs.meteor.com/api/pubsub.html#Subscription-added ...

Meteor.publish('companies', function(limit) {
  var subscription = this;
  db.collection('companies').aggregate([{ $group: { _id: { location: "$google_maps.geometry_location" }, companies: { $addToSet: { name: "$company_name" } }, count: { $sum: 1} } }, { $match: { count: { $gt: 1 } } }]).toArray((err, result) => {
      subscription.added('companies-aggregate', 'geometry-grouping', {result: result});
  });

});

// On the client:
var CompaniesAggregate = new Mongo.Collection('companies-aggregate');

// Inside a reactive context, like a helper
var result = CompaniesAggregate.findOne('geometry-grouping').result;

Naturally, to make it reactive, you'd have to know when the results of the aggregations would change. There is no automatic way to do that--you would have to resolve that logically, with your own code.

The best way to do that is to save the subscription variable in an array somewhere in a higher scope, and called changed on all the subscriptions for 'companies' for the geometry-grouping document, computing an updated result.

The commenter's solution won't be realtime; in other words, if one user makes a change to the e.g. company name or location, another user won't see those changes.

Upvotes: 3

Related Questions