【问题标题】:Mongoose OR operator for schema definitions用于模式定义的 Mongoose OR 运算符
【发布时间】:2013-11-18 10:06:35
【问题描述】:

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

例如,things 属性只能包含以下两种模式之一:

new Schema({
    things: [{
        requiredProp: String,
        otherProp: Number
    }, {
        otherOption: Number
    }]
});

换句话说,我不想只允许 anything (AKA Schema.Types.Mixed) 存储在此属性中,而只允许这两个可能的定义。

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

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    您应该只在模式的数组类型中定义一个字典,然后使用 mongoose 模式类型逻辑设置它们是否需要。如果您想执行更多逻辑以确保已设置任一字段,请使用预保存,如下所示:

    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 均未设置,则会返回错误。

    【讨论】:

      猜你喜欢
      • 2016-02-02
      • 2015-10-16
      • 2016-07-01
      • 2015-07-08
      • 1970-01-01
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 2016-06-14
      相关资源
      最近更新 更多