我有一个包含子项(Widget)的父模式(仪表板)。
问题是我需要验证单个窗口小部件,但.pre('save')
接收窗口小部件数组。
有没有办法验证单一财产?我试图添加widgetSize: { type: String, validate: xxx }
,但没有运气。
var widgetSchema = new Schema({
_id: Schema.Types.ObjectId,
measurement: { type: String, required: true },
type: { type: String, required: true },
key: { type: String, default: '' },
background: { type: Schema.Types.Mixed, default: false },
localeId: { type: Schema.Types.Mixed, default: false },
hintText: String,
widgetSize: { type: String }
});
widgetSchema.pre('save', function (next) {
console.log(this);
if(!sizeValidator(this.widgetSize)) {
return next(new Error('Size format was incorrect: ' + this.widgetSize));
}
next();
});
var dashboardSchema = new Schema({
slug: { type: String, required: true },
name: { type: String, required: true },
backgroundImage: String,
defaultDashboard: { type: Boolean, default: false },
backgroundColor: String,
widgets: [widgetSchema]
});
添加子文档的代码
dashboard.widgets.push(widgetToCreate);
return dashboard.saveAsync(); // promisified
答案 0 :(得分:0)
看起来您正在使用this
来验证您注意到的suboc值设置为顶级文档。更直接地说,您可以使用传递给validate函数的值,如下所示:
var widgetSchema = new Schema({
_id: Schema.Types.ObjectId,
measurement: {
type: String,
required: true
},
type: {
type: String,
required: true
},
key: {
type: String,
default: ''
},
background: {
type: Schema.Types.Mixed,
default: false
},
localeId: {
type: Schema.Types.Mixed,
default: false
},
hintText: String,
widgetSize: {
type: String,
validate: function widgetSizeValidate(val) {
return val === 'foobar';
}
}
});