【发布时间】:2016-05-28 08:51:33
【问题描述】:
我有两个模型用户和计划。用户有很多计划,所以在我的 Mongoose Schema 中,我嵌入了如下所示的用户 ID。
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 和 plan.js)中有两个单独的控制器,用于处理用户和计划(/api/users 和 /api/plans)的 api 路由。
如果我有特定用户的用户 ID,我正在努力弄清楚如何找到特定用户的计划。
我应该在用户控制器中创建路由 /api/users/:id/plans 还是有办法在像 /api/plans/search 这样的 plan.js 控制器中创建搜索路由?=
或者有其他方法吗?
这是我的计划控制器代码:
计划
// 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);
});
});
不确定什么是最好的方法。非常感谢您的意见。
【问题讨论】:
标签: javascript node.js express mongoose mean