我有以下情况:
var aField1 = new Schema({
//Stuff1
});
var aField2 = new Schema({
//Stuff2
});
var MainSchema = new Schema({
aField: { type: Schema.Types.Mixed, required: true},
});
我的问题是:
a)是否可以定义' aField1' AND' aField2'对于' aField'有效的架构不使用混合?
b)如果是,是否可以验证这两种情况?
祝你好运
答案 0 :(得分:0)
我知道这不太理想,但也许您可以使用Mongoose Custom Validators来实现这一点,例如:
var aField1Schema = new Schema({});
var aField2Schema = new Schema({});
var MainSchema = new Schema({
aField: {type: Schema.Types.Mixed, required: true, validate: models(['aField1', 'aField2'])}
});
mongoose.model('aField1', aField1Schema);
mongoose.model('aField2', aField2Schema);
mongoose.model('Main', MainSchema);
function models(possibleModels) {
return [function(value) {
return possibleModels.indexOf(value.constructor.name) === 0;
}, 'validation of `{PATH}` failed with value `{VALUE}`'];
}
然后创建文档,您可以这样做:
var doc = new Main({});
doc.aField = new aField2({});
doc.save();