3

Below is my publish function which is pretty much a copy from Average Aggregation Queries in Meteor

What it's used for: display a list of documents. The user can then click on one item (restaurant) and can look at the details. Within the details there are arrows previous and next which would allow to cicle through the list.

My idea was to use that aggregation method to enrich every document with the previous and next document id, that way I could easily build my previous and next links.

But how? I have no idea. Maybe there is a better way?

Meteor.publish("restaurants", function(coords, options) {
    if (coords == undefined) {
        return false;
    }
    if (options == undefined) {
        options = {};
    }
    if (options.num == undefined) {
        options.num = 4
    }
    console.log(options)
    /**
     * the following code is from https://stackoverflow.com/questions/18520567/average-aggregation-queries-in-meteor
     * Awesome piece!!!
     * 
     * */
    var self = this;
    // This works for Meteor 1.0
    var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    // Your arguments to Mongo's aggregation. Make these however you want.
    var pipeline = [
        {
         $geoNear: {
            near: { type: "Point", coordinates: [ coords.lng , coords.lat ] },
            distanceField: "dist.calculated",
            includeLocs: "dist.location",
            num: options.num,
            spherical: true
         }
       }
    ];

    db.collection("restaurants").aggregate(        
        pipeline,
        // Need to wrap the callback so it gets called in a Fiber.
        Meteor.bindEnvironment(
            function(err, result) {
                // Add each of the results to the subscription.
                _.each(result, function(e) {
                    e.dist.calculated = Math.round(e.dist.calculated/3959/0.62137*10)/10;
                    self.added("restaurants", e._id, e);
                });
                self.ready();
            },
            function(error) {
                Meteor._debug( "Error doing aggregation: " + error);
            }
        )
    );
});
Community
  • 1
  • 1
rapsli
  • 749
  • 1
  • 8
  • 23

1 Answers1

0

If you don't have a lot of documents on result, you can do that with JavaScript. Change your subscription code to something like this (I didn't test this code).

_.each(result, function(e, idx) {
  if(result[idx - 1]) e.prev = result[idx - 1]._id;
  if(result[idx + 1]) e.next = result[idx + 1]._id;
  e.dist.calculated = Math.round(e.dist.calculated/3959/0.62137*10)/10;
  self.added("restaurants", e._id, e);
});
Thanish
  • 309
  • 2
  • 5