MongoDB Aggregation adds the following document (Meteor app)

Below is my publish function which is pretty much a copy of the Average Aggregate Queries in Meteor

What he used to: display a list of documents. The user can then click on one item (restaurant) and see the details. Inside the parts there are previous and next arrows that will allow you to scroll through the list.

My idea was to use this aggregation method to enrich each document with the previous and next document ID so I could easily create 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 /questions/352462/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 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);
            }
        )
    );
});

      

+3


source to share


1 answer


If you don't have a lot of documents on the result, you can do it with JavaScript. Change your subscription code to something like this (I haven't tested 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);
});

      

0


source







All Articles