我正在开发一个应用程序,我必须按sportsname过滤。我是 在后端使用Node.js和MongoDB。
这是我的代码: -
router.route('/user/:_id/explore/:sportsname')
.get(function(req, res){
var query = Host.find();
if(req.params.sportsname){
query.where({sportsname:decodeURIComponent(req.params.sportsname)});
}
query.exec(function(err, explore){
if(err)
return next(err);
res.json(sportsname);
console.log(sportsname);
})
这是文件。我想通过sportsname
搜索用户
[
{
"_id":"5460e2af4ee5216f17000061",
"maxplayer":"1",
"minplayer":"11",
"date":"10 August 2014",
"venue":"google",
"time":"Afternoon",
"sportsname":"Lawn Tennis",
"__v":0
},
{
"_id":"5460ff1b4ee5216f17000065",
"maxplayer":"0",
"minplayer":"9",
"date":"10 October 2014",
"venue":"google",
"time":"Early Morning",
"sportsname":"Cricket",
"__v":0
},
{
"_id":"5461a4014ee5216f17000089",
"maxplayer":"4",
"minplayer":"29",
"date":"13 December 2014",
"venue":"google",
"time":"Afternoon",
"sportsname":"Lawn Tennis",
"__v":0
}
]
当我在那段时间跑步时,它会发出错误。错误如下: -
TypeError: path must be a string at Query.where
(/node/node-api-master/node_modules/mongoose/lib/query.js:593:11)
at Object.handle (/node/node-api-master/server.js:202:19) at next_layer
(/node/node-api-master/node_modules/express/lib/router/route.js:103:13)
at Route.dispatch (/node/node-api-master/node_modules/express/lib/router/route.js:107:5)
at /node/node-api-master/node_modules/express/lib/router/index.js:195:24
at param (/node/node-api-master/node_modules/express/lib/router/index.js:268:14)
at param (/node/node-api-master/node_modules/express/lib/router/index.js:280:16)
at param (/node/node-api-master/node_modules/express/lib/router/index.js:280:16)
at Function.proto.process_params
(/node/node-api-master/node_modules/express/lib/router/index.js:296:3)
at next (/node/node-api-master/node_modules/express/lib/router/index.js:189:19)
答案 0 :(得分:0)
这是一个语法问题,这是您正在尝试做的正确实现:
router.get('/user/:_id/explore/:sportsname', function(req, res, next) {
return Host.find({ sportsname: req.params.sportsname }, function(err, users) {
if (err) return next(err);
console.log(users);
return res.json(users);
});
});
请注意,检查是否存在req.params.sportsname
是不必要的,因为如果不是,则永远不会到达您的路线。如果您想使此参数可选,请使用以下内容:/user/:_id/explore/:sportsname?
(在参数后添加问号。