2017-03-08 5 views
0

私は、このスキーマがあります。マングースネストされた文書の検証

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 
var restaurantSchema = new Schema({ 
    working_hours: { 
     weekday: { 
      start: String, 
      end: String 
     }, 
     weekend: { 
      start: String, 
      end: String 
     } 
    } 
}); 

を、私はweekdayweekendのそれぞれについてstartendフィールドを検証したいと思います。 私は現在、以下のように正規表現を使用したので、非常に明示的にやっている:これより良い方法があるように持って

restaurantSchema.path('working_hours.weekday.start').validate(function(time) { 
    var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/; 
    return timeRegex.test(time); 
}, 'Time must be in the format `hh:mm` and be a valid time of the day.'); 

restaurantSchema.path('working_hours.weekday.end').validate(function(time) { 
    var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/; 
    return timeRegex.test(time); 
}, 'Time must be in the format `hh:mm` and be a valid time of the day.'); 

restaurantSchema.path('working_hours.weekend.start').validate(function(time) { 
    var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/; 
    return timeRegex.test(time); 
}, 'Time must be in the format `hh:mm` and be a valid time of the day.'); 

restaurantSchema.path('working_hours.weekend.end').validate(function(time) { 
    var timeRegex = /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/; 
    return timeRegex.test(time); 
}, 'Time must be in the format `hh:mm` and be a valid time of the day.'); 

。何か案は?

答えて

1

mongooseのカスタム検証を利用すると、再利用できるカスタム検証オブジェクトをラップすることができます。これは定型文全体を減らすはずです。 Mongoose validation docsを参照してください。

const dateValidation = { 
    validator: (value) => /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/.test(value), 
    message: 'Time must be in the format hh:mm and be a valid time of the day.' 
} 

var restaurantSchema = new Schema({ 
    working_hours: { 
     weekday: { 
      start: {type: String, validate: dateValidation}, 
      end: {type: String, validate: dateValidation} 
     }, 
     weekend: { 
      start: {type: String, validate: dateValidation}, 
      end: {type: String, validate: dateValidation} 
     } 
    } 
}); 
+0

これははるかに優れた選択肢です。ありがとうございます! – SalmaFG

関連する問題