Ben*_*Ben 5 validation mongoose node.js express
我有一个接受JSON帖子的rest api资源.例:
{
"location": {
"coordinates": [
-122.41941550000001,
37.7749295
]
}
Run Code Online (Sandbox Code Playgroud)
然后通过Express从请求中收集坐标:
module.exports.create = function(req, res, next) {
var coordinates = req.body.location.coordinates;
....
Run Code Online (Sandbox Code Playgroud)
然后将它们提交给Mongoose模型.我正在编写测试,其中location.coordinates缺少例如
{
"foo": {
"bar": [
-122.41941550000001,
37.7749295
]
}
Run Code Online (Sandbox Code Playgroud)
然后,在模型的验证部分中失败:
locationSchema.path('location.coordinates').validate(function(coordinates){
^
TypeError: Cannot call method 'validate' of undefined
Run Code Online (Sandbox Code Playgroud)
所以我的问题是如何验证输入是否正确?是否应该在到达模型之前在路线中完成,还是应该在模型中完成?任何如何例子也将被赞赏.
作为参考,Mongoose模型看起来像:
var locationSchema = new Schema({
userid: { type: Number, required: true },
location: {
type: [{
type: "String",
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
}], required: true,
coordinates: { type: [Number], required:true }
},
create_date: { type: Date, default: Date.now }
});
locationSchema.path('location.coordinates').validate(function(coordinates){
...
}, 'Invalid latitude or longitude.');
Run Code Online (Sandbox Code Playgroud)
我的典型方法是在路由和模型之间引入服务层,这就是验证发生的地方.不要在"网络服务"意义上考虑"服务"; 它只是提供给定域的抽象级别.这有以下好处:
这是一个简单的例子,它可能是这样的:
location-service.js
var locationService = module.exports = {};
locationService.saveCoordinates = function saveCoordinates(coords, cb) {
if (!isValidCoordinates(coords)) {
// your failed validation response can be whatever you want, but I
// like to reserve actual `Error` responses for true runtime errors.
// the result here should be something your client-side logic can
// easily consume and display to the user.
return cb(null, {
success: false,
reason: 'validation',
validationError: { /* something useful to the end user here */ }
});
}
yourLocationModel.save(coords, function(err) {
if (err) return cb(err);
cb(null, { success: true });
});
};
Run Code Online (Sandbox Code Playgroud)
some-route-file.js
app.post('/coordinates', function(req, res, next) {
var coordinates = req.body.location.coordinates;
locationService.saveCoordinates(coordinates, function(err, result) {
if (err) return next(err);
if (!result.success) {
// check result.reason, handle validation logic, etc.
} else {
// woohoo, send a 201 or whatever you need to do
}
});
});
Run Code Online (Sandbox Code Playgroud)
我已经将此结构应用于3或4个不同的Web应用程序和API,并且已经非常喜欢它.
| 归档时间: |
|
| 查看次数: |
2632 次 |
| 最近记录: |