【发布时间】:2014-12-03 17:37:50
【问题描述】:
我有一个接受 JSON 帖子的 rest api 资源。示例:
{
"location": {
"coordinates": [
-122.41941550000001,
37.7749295
]
}
然后由 Express 从请求中收集坐标:
module.exports.create = function(req, res, next) {
var coordinates = req.body.location.coordinates;
....
然后将这些提交给 Mongoose 模型。我正在针对缺少 location.coordinates 的地方编写测试,例如
{
"foo": {
"bar": [
-122.41941550000001,
37.7749295
]
}
然后在模型的验证部分失败:
locationSchema.path('location.coordinates').validate(function(coordinates){
^
TypeError: Cannot call method 'validate' of undefined
所以我的问题是如何验证输入是否正确?这应该在到达模型之前在路线中完成,还是应该在模型中完成?任何有关如何的示例也将不胜感激。
作为参考,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.');
【问题讨论】:
标签: node.js validation express mongoose