我有这个结构:
{
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中实现这一点吗?
答案 0 :(得分:11)
不确定这是否为时已晚,但我认为你需要的是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
}
}));