快递的通用路由处理程序

时间:2015-04-01 11:45:07

标签: node.js generics express mongoose

我正在尝试在Express应用程序中为REST样式路由制作一些通用处理程序。

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

下面的代码是最明显的尝试,显示了我尝试做的事情,但显然失败了,因为Model在匿名函数的范围内丢失了。

/**
 * Model is a Mongoose model object
 */
routeDefinitions: function (resourceName, Model) {
    routePath = api_prefix + resourceName.toLowerCase();

    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)
    }
}

我已经看了几个选项,对于Node / Express和Connect中间件来说还是一个新手,所以可能会有更明显的东西丢失。

1 个答案:

答案 0 :(得分: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)
    }
}