Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add conditional schema based on other field?

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?

like image 673
Momos Morbias Avatar asked May 03 '16 08:05

Momos Morbias


1 Answers

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

like image 55
DucDigital Avatar answered Nov 02 '22 18:11

DucDigital