21

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?

3
  • 1
    See mongoosejs.com/docs/validation.html#update-validators-and-this Commented May 3, 2016 at 9:21
  • @str it's not enought for me because i want to be able to plug schema (and enjoy the benefits of mongoose schemas) instead of doing the validation by my self. Commented May 3, 2016 at 10:26
  • 1
    As far as I know, it is not possible to create dynamic schemas the way you want it. So custom validation is your only option. Commented May 3, 2016 at 10:33

1 Answer 1

23

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.