I have this structure:
{
personFullName: String,
personMobileOS: Number // 1 = IOS, 2 = Android,
moreDetails: Mixed
}
I want to add conditional schema based on other field like this:
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
}
}
As you can see, the schema for "moreDetails" is conditional, it's possible to achieve this in mongoose?
Not sure if it's too late for this but I think what you need is mongoose subdocument discriminator. This allow you to have 2 different schema on subdocument, mongoose will take care of schema mapping, include the validation.
Yes, what you need to archive in this question is a long standing issue and has been requested since mongoose 3.0. And now it's official :)
An example with a new mongoose subdocument discriminator:
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
}
}));
Also checkout this blog post for more details
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With