我正在尝试在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中间件来说还是一个新手,所以可能会有更明显的东西丢失。
答案 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)
}
}