【发布时间】:2016-05-31 11:11:55
【问题描述】:
我有两个独立的模式 - 1. 用户 2. 计划。我正在尝试查找属于某个用户的所有计划,但使用查询参数执行获取请求不起作用。请帮助。
这是我的查询
http://localhost:8080/api/plans/search?userId=56bd16761e6bb0e5b2b43c9b
我通过这条路线得到了所有的计划,所以这行得通。
http://localhost:8080/api/plans/
这是我的计划模型
var PlanSchema = new mongoose.Schema({
title: {type: String},
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
spots:[{
name: {type: String},
category: {type: String},
address: {type: String},
hours: {type: String},
phone: {type: String},
website: {type: String},
notes: {type: String},
imageUrl: {type: String},
dayNumber: {type: Number}
}]
});
这是我的计划路线。
PlansController.get('/', function(req, res){
Plan.find({}, function(err, plans){
res.json(plans);
});
});
PlansController.get('/:id', function(req, res){
Plan.findOne({_id: req.params.id}, function(err, plan){
res.json(plan);
});
});
PlansController.get('/search', function(req, res){
Plan.find({ userId: req.query.userId }, function (err, plans){
res.json(plans);
});
});
我做错了什么?在终端我得到这个,
GET /api/plans/search?userId=56bd16761e6bb0e5b2b43c9b 200 7.047 毫秒 - -
【问题讨论】:
-
如果你这样做
console.log(req.query.userId)你会得到什么? -
@AshleyB console.log 会在哪里输出?抱歉,我是节点新手。如果终端应该记录错误,那么当我发出请求时,终端上没有任何内容。
-
就在您的
/search路线的开始处(Plan.find(..)之前) -
@AshleyB 我的意思是我这样做了,但它没有输出任何东西。这是sn-p
PlansController.get('/search', function(req, res){ console.log(req.query.userId); res.json(req.query.userId); Plan.find({ userId: req.query.userId }, function (err, plans){ res.json(plans); }); }); -
我想我明白了。由于搜索路由看起来类似于 /:id 路由,因此它不断拉取该路由以查找搜索字符串。搜索路由必须包含在 /:id 路由之前。
标签: node.js mongodb express mongoose mean