2017-03-08 155 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