2015-04-01 58 views
0

我想在快速应用程序中为REST样式路由制作一些通用处理程序。明确的通用路由处理程序

它们被定义在一个对象中,然后它与在特定路径文件中定义的属性合并。属性的合并工作正常。我的问题是以某种方式将我的模型对象传递给处理程序的匿名函数。

下面的代码是最明显的尝试,显示我正在尝试做什么,但显然失败,因为Model在匿名函数的作用域中丢失。我看了几个选项,并且Node/Express和Connect中间件还是比较新的,所以可能会有更明显的东西丢失。

回答

0

我通过简单地调用mongoose.model解决该问题:

routeDefinitions: function (resourceName) { 
    routePath = api_prefix + resourceName.toLowerCase(); 
    var modelName = inflect.singularize(resourceName); 
    var Model = mongoose.model(modelName); 

    var routeProperties = { 
     getById: { 
      method: 'get', 
      isArray: false, 
      auth: true, 
      url: routePath + '/:id', 
      handlers: [function (req, res, next) { 
       Model.findById(req.param('id')).exec(res.handle(function (model) { 
        console.log(model); 
        res.send(model); 
       })); 
      }] 
     }, 
     getAll: { 
      method: 'get', 
      isArray: true, 
      auth: true, 
      url: routePath, 
      handlers: [function (req, res, next) { 
       Model.find().exec(res.handle(function (model) { 
        res.send(model); 
       }));   
      }] 
     }, 
     //... (create, update, delete etc) 
    } 
} 
相关问题