Node.js 带有/:id输入的快速路由返回空数组

Node.js 带有/:id输入的快速路由返回空数组,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我试图让我的API将id作为输入,并根据给定的id从mongoDB返回结果 我的示例集合如下所示: id: 1 { count: 5 } id: 2 { count: 10 } var tripSchema = new Schema({ _id: Number, count: Number }, {collection: 'test'} ); 我的猫鼬模式如下所示: id: 1 { count: 5 } id: 2 { count: 10 }

我试图让我的API将
id
作为输入,并根据给定的
id
从mongoDB返回结果

我的示例集合如下所示:

id: 1 {
   count: 5
}
id: 2 {
   count: 10
}
var tripSchema = new Schema({
    _id: Number,
    count: Number
},
    {collection: 'test'}
);
我的猫鼬模式如下所示:

id: 1 {
   count: 5
}
id: 2 {
   count: 10
}
var tripSchema = new Schema({
    _id: Number,
    count: Number
},
    {collection: 'test'}
);
我为这条路线创建了另一个文件,我认为错误在于:

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); 
        });
    });
}
现在使用postman,我尝试获取
/trips/72
,但这会导致一个空数组
[]
,数据库中有一个
\u id
72的条目,对应的计数如上所示。我的问题是,这是否是正确的方法,我在这里做错了什么

--更新:
匹配
阶段或整个
聚合
似乎有问题。我选择了猫鼬的
findById
,现在它可以使用了:

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

req.params.id
以字符串形式返回您的id,而我认为在聚合
match
部分中,您需要将其作为ObjectId传递。因此,您应该将其转换为ObjectId:

$match: { _id: ObjectId(req.params.id) }

请尝试
parseInt(req.params.id)
?这会导致“传入的参数必须是一个12字节的字符串或一个24个十六进制字符的字符串”错误。请
console.log(req.params.id)
并检查它是否包含有效的id值。是的,这样调用时会打印“72”:
trips/72
。72在mongoDB集合中也是一个有效的“_id”,但仅为72,未使用ObjectID(“72”)进行排序。这可能是原因。是否对
\u id
使用自定义值?因为72不是有效的对象id,因此对其执行
ObjectId()
操作将始终引发错误。确定。在这种情况下,如果您将_id存储为字符串,您可以简单地使用
match:{_id:req.params.id}
或者如果您将_id存储为数字,那么您可以使用
match:{_id:parseInt(req.params.id)}