[英]MEAN Stack: Expressjs Routes with query parameters
I have two separate schemas- 1. User 2. Plans. 我有两个独立的模式-1.用户2.计划。 I am trying to find all the plans that belong to a user, but doing a get request using query parameters is not working.Please help. 我正在尝试查找属于用户的所有计划,但是使用查询参数执行get请求无法正常工作。请帮助。
Here is my query 这是我的查询
http://localhost:8080/api/plans/search?userId=56bd16761e6bb0e5b2b43c9b http:// localhost:8080 / api / plans / search?userId = 56bd16761e6bb0e5b2b43c9b
I get all the plans via this route so that is working. 我通过这条路线获得了所有计划,因此可以正常工作。
http://localhost:8080/api/plans/ http:// localhost:8080 / api / plans /
Here is my Plan Model 这是我的计划模型
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}
}]
});
Here is my Plans Route. 这是我的计划路线。
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);
});
});
What am I doing wrong? 我究竟做错了什么? In the terminal I get this, 在终端我得到这个,
GET /api/plans/search?userId=56bd16761e6bb0e5b2b43c9b 200 7.047 ms - - GET / api / plans / search?userId = 56bd16761e6bb0e5b2b43c9b 200 7.047 ms--
I think I figured it out. 我想我知道了。 since search route looks similar to /:id route, it keeps thinking of search strings as IDs and keeps using the id route. 由于搜索路由看起来类似于/:id路由,因此它一直将搜索字符串视为ID并继续使用id路由。 Search Route has to be included before the /:id route. 搜索路由必须包含在/:id路由之前。
Here is the updated code. 这是更新的代码。
PlansController.get('/search', function(req, res){
console.log(req.query.userId);
Plan.find({ userId: req.query.userId }, function (err, plans){
console.log(plans);
res.json(plans);
});
});
PlansController.get('/:id', function(req, res){
Plan.findOne({_id: req.params.id}, function(err, plan){
res.json(plan);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.