如何基于其他字段添加条件架构?

Mom*_*ias 16 mongoose mongodb node.js

我有这个结构:

{
    personFullName: String,
    personMobileOS: Number // 1 = IOS, 2 = Android,
    moreDetails: Mixed
}
Run Code Online (Sandbox Code Playgroud)

我想基于其他字段添加条件架构,如下所示:

if (personMobileOS === 1) { // IOS
    moreDetails = { 
        iosVersion: Number, 
        loveApple: Boolean
    }
} else if (personMobileOS === 2) { // Android
    moreDetails = {
        wantToSell: Boolean,
        wantToSellPrice: Number
        wantToSellCurrency: Number // 1 = Dollar, 2 = Euro, 3 = Pound
    }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,"moreDetails"的模式是有条件的,可以在mongoose中实现这一点吗?

Duc*_*tal 12

不确定是否为时已晚,但我认为你需要的是mongoose subdocument discriminator.这允许您在子文档上有2个不同的模式,mongoose将负责模式映射,包括验证.

是的,你需要在这个问题中存档是一个长期存在的问题,并且自mongoose 3.0以来一直被要求.现在它正式:)

一个新的mongoose子文档鉴别器的示例:

const eventSchema = new Schema({ message: String },
  { discriminatorKey: 'kind' });

const Event = mongoose.model('Event', eventSchema);

const ClickedEvent = Event.discriminator('Clicked', new Schema({
  element: {
    type: String,
    required: true
  }
}));

const PurchasedEvent = Event.discriminator('Purchased', new Schema({
  product: {
    type: String,
    required: true
  }
}));
Run Code Online (Sandbox Code Playgroud)

另请查看此博客文章以获取更多详细信息