我有一个休息api资源,接受一个JSON文章。例如:Node.js,Express,Mongoose - 输入验证 - 在路由或模型中?
{
"location": {
"coordinates": [
-122.41941550000001,
37.7749295
]
}
的坐标被从请求快报然后收集:
module.exports.create = function(req, res, next) {
var coordinates = req.body.location.coordinates;
....
然后这些提交给猫鼬模型。我正在写这个地方的坐标缺失的测试,例如
locationSchema.path('location.coordinates').validate(function(coordinates){
^
TypeError: Cannot call method 'validate' of undefined
所以我的问题是如何将我验证输入的是正确的:
{
"foo": {
"bar": [
-122.41941550000001,
37.7749295
]
}
这然后用模型的验证部分中失败了呢?在进入模型之前应该在路线中完成这项工作,还是应该在模型中完成?任何如何的例子也将不胜感激。
仅供参考猫鼬模型看起来像:
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.');
绝对保存作为一个片段! – xShirase 2014-10-08 22:56:47
@ jmar777 - 那很有帮助。介绍该抽象层在我的应用程序中很有意义。感谢您抽出宝贵时间分享您的想法,这对我帮助很大! – Ben 2014-10-08 23:31:19