Mongodb 模式定义的Mongoose或运算符

Mongodb 模式定义的Mongoose或运算符,mongodb,mongoose,Mongodb,Mongoose,Mongoose是否支持,或者是否有一个可用的包支持数组中嵌入模式的多个“选项” 例如,things属性只能包含两个模式中的一个: new Schema({ things: [{ requiredProp: String, otherProp: Number }, { otherOption: Number }] }); 换句话说,我不想只允许任何东西(又称Schema.Types.Mixed)存储在此属性中,而只允许这两

Mongoose是否支持,或者是否有一个可用的包支持数组中嵌入模式的多个“选项”

例如,things属性只能包含两个模式中的一个:

new Schema({
    things: [{
        requiredProp: String,
        otherProp: Number
    }, {
        otherOption: Number
    }]
});
换句话说,我不想只允许任何东西(又称Schema.Types.Mixed)存储在此属性中,而只允许这两种可能的定义


或者,是否存在架构设计建议以避免此问题?

您应该只在架构的数组类型中定义一个dict,然后使用mongoose架构类型逻辑设置它们是否是必需的。如果要执行更多逻辑以确保已设置其中一个字段,请使用pre save,如下所示:

var MySchema = new Schema({
    things: [{
        requiredProp: {type: String, required: true},
        otherProp: Number,
        otherOption: Number,
    }]
});

MySchema.pre('save', function(next) {
    if (!this.otherProp && !this.otherOption) {
        next(new Error('Both otherProp and otherOption can\'t be null'))
    } else {
        next()
    }
})
如果未设置otherProp或otherOption,则在保存对象时将返回错误