2016-02-16 43 views
0

我有两个模型用户和计划。用户有很多计划,所以在我的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); 
    }); 
}); 

不知道什么是最好的办法。将不胜感激一些输入。

回答

1

1)如果你想创建这个路径“/ API /用户/:ID /计划”,那么你需要嵌入计划阵列成这样,用户模式 ​​-

var Schema = mongoose.Schema; 

var UserSchema = new mongoose.Schema({ 
    ... 
    plans: { type: [Schema.ObjectId], ref: 'Plan' }, 
    ... 
}); 
mongoose.model('User', UserSchema); 

现在你可以很容易地填充通过运行这个查询从计划模式的计划 -

User.findOne({ _id: userId}) 
    .populate('plans') 
    .exec(function(err, user){ 
    //do stuff 
    }); 

如果计划用户可以不是无限期的,那么你可以利用这一点,因为MongoDB的文件有16 MB和数组的大小限制是生长超出界限的数量应不包含在模式中。

2)对于使用“/ API /计划/搜索?用户ID =”你需要存储用户id在计划模式。如下所述,您应该对模式进行一些更改。

var PlanSchema = new mongoose.Schema({ 
    title: {type: String}, 
    userId: { type: Schema.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} 
    }] 
}); 

因此,在未来,如果你需要的用户数据,你可以使用不运行嵌套查询上述同样的方法轻松地填充它。

希望有所帮助。

+0

谢谢,图沙尔。如果计划不是无限的,你认为哪种方法更好。使用第二种方法有缺点吗? – manutdfan