我有这个结构:
{
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 中实现?
最佳答案
不确定是否为时已晚,但我认为您需要的是 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
}
}));
关于node.js - 如何根据其他字段添加条件模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36999377/