Tuesday, 23 May 2017

Add fields to mongoose aggregation dynamically based on req params

I am building an API where 3 input parameters can be specified, such as: /trips/:id/:from/:to. The parameters I am interested in especially are from and to. In my mongoDB collection, I have a structure like the following:

id    2014_08     2014_09     ...
1     [...]       [...]
2     [...]       [...]

Now what I want to achieve in the following aggregation, is that based on what is requested from the call in from and to, it should return the corresponding fields.

For example: GET /trips/1/2014_08/2014_09 should return:

id: 1,
2014_08: {
    ...
},
2014_09: {
    ...
}

My route looks like this:

app.get('/trips/:id/:from/:to', function(req,res) {
    var aggr = Trip.aggregate([
        {   "$match": {
                "_id": Number(req.params.id)
            }
        },{
                "$project": {
                "_id"  : 1,
                "trips_201408": "$2014_08",
                //How to append more to this, according to from/to?
            }
        }
    ])
        aggr.options = { allowDiskUse: true };
        aggr.exec(function(err, trips){
        if(err)
            res.send(err);
        res.json(trips); 
    });
});

So my question is, what a good practice for creating project stages dynamically corresponding to the input of from and to?



via ffritz

No comments:

Post a Comment