如何添加基于其他领域的条件模式?

我有这样的结构:

{ personFullName: String, personMobileOS: Number // 1 = IOS, 2 = Android, moreDetails: Mixed } 

我想添加像这样的其他领域的条件架构:

 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 } } 

正如你所看到的,“moreDetails”的模式是有条件的,有可能在mongoose中实现这一点?

不知道这是为时已晚,但我认为你需要的是mongoosesubdocument鉴别 。 这允许你在子文档上有两个不同的模式,mongoose会照顾模式映射,包括validation。

是的,你需要在这个问题上存档是一个长期存在的问题,并要求从mongoose3.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 } })); 

也检查这个博客文章的更多细节