给定一个 nodejs、mongoose、mongodb、expressjs 设置,我们拥有验证特定请求的权限/安全相关路由。例如:
permissionUtils.checkStudentWritePermissions = function(req, res, next){
//load this student from the mongoose db
//ensure the current user has permission to update this student
}
server.put("/api/student/:studentId/enroll",
permissionUtils.checkStudentWritePermissions, function(req, res, next){
//load student from the database, validate the changes
//update student in mongodb, send new version back to user
});
中间件很有用,因为我们确保当前用户在任何情况下都有权更新学生。(代码重用等)您会注意到,在这两个示例中,我都是从 mongodb 加载学生。是否有一种可接受的模式来避免这种双重加载?某种请求周期缓存或传递模型的巧妙方式?