2017-03-08 212 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 
     } 
    } 
}); 

,我想驗證startend領域的每一個weekdayweekend。 我目前這樣做非常明確使用如下正則表達式:

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