Reputation: 2261
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);
});
Upvotes: 0
Views: 384
Reputation: 10083
req.params.id
returns your id in String form, while I think in aggregate match
section you need to pass it as ObjectId. So, you should convert it to ObjectId:
$match: { _id: ObjectId(req.params.id) }
Upvotes: 1