Friday 19 May 2017

Express Route with /:id input returns empty array

I am trying to have my API take an id as input and return results from mongoDB according to the id given.

My example collection looks like this:

id: 1 {
   count: 5
}
id: 2 {
   count: 10
}

My mongoose Schemas looks like this:

var tripSchema = new Schema({
    _id: Number,
    count: Number
},
    {collection: 'test'}
);

And I created another file for this route, where I think the error lies in:

module.exports = function(app) {
    app.get('/trips/:id', function(req,res) {
        console.log(req.params.id); // Does print the ID correctly
            var aggr = Trip.aggregate([
                {   "$match": {
                        "_id": {
                            "$eq": req.params.id
                        }
                     }
                },
                {
                "$project": {
                    "_id"  : 1,
                    "count": "$count"
                }
            }
            ])
            aggr.options = { allowDiskUse: true };
            aggr.exec(function(err, stations){
            if(err)
                res.send(err);
            res.json(stations); 
        });
    });
}

Now using postman I try to GET /trips/72, but this results in an empty array [], there is an entry in the DB for _id 72 with a corresponding count just like above. My question is if this is the correct approach and what I am doing wrong here.

--Update: There seems to be something wrong with either the match stage or the whole aggregation. I opted for mongoose's findById, and with this it works now:

    Trip.findById(req.params.id, function (err, doc){
      res.json(doc);
    });



via ffritz

No comments:

Post a Comment