我有一個休息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