Mongoose嵌套文档验证

时间:2017-03-08 14:47:51

标签: node.js mongodb mongoose

我有这个架构:

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的{​​{1}}和weekday字段。 我目前非常明确地使用正则表达式,如下所示:

weekend

必须有比这更好的方法。有什么想法吗?

1 个答案:

答案 0 :(得分: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}
        }
    }
});