我有两个模型用户和计划。用户有很多计划,所以在我的Mongoose模式中,我正在嵌入像下面这样的用户ID。MEAN堆栈:如何为嵌套关系创建路由?
var PlanSchema = new mongoose.Schema({
title: {type: String},
userId: {type: String},
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}
}]
});
我在不同的文件(users.js和plans.js)为用户和计划(/ API /用户/ API /计划)处理API路线两个独立的控制器。
我很想搞清楚如果我有他们的用户ID,我可以找到特定用户的计划。
我应该创建一个路由/ API /用户/:ID /在用户控制计划或者是有办法创造plans.js控制器搜索路线像/ API /计划/搜索=
?还是有不同的方式?
这是我的计划,控制器代码:
计划
// Routes
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.delete('/:id', function(req, res){
var id = req.params.id;
Plan.findByIdAndRemove(id, function(){
res.json({status: 202, message: 'Success'});
});
});
PlansController.post('/', function(req, res){
var plan = new Plan(req.body);
plan.save(function(){
res.json(plan);
});
});
PlansController.patch('/:id', function(req, res){
Plan.findByIdAndUpdate(req.params.id, req.body, {new: true}, function(err, updatedPlan){
res.json(updatedPlan);
});
});
不知道什么是最好的办法。将不胜感激一些输入。
谢谢,图沙尔。如果计划不是无限的,你认为哪种方法更好。使用第二种方法有缺点吗? – manutdfan