Search code examples
mongodbvalidationmongodb-schema

Peer Based Validation in MongoDB Schema


I am using MongoDB Schema to validate the data inserted into the database. I would like to have peer based validation similar to Joi.when() in Joi. Here is how the data looks like:

first:"Teddy",
last:"Bear"

How would I make last required and have maxLength:10 only if the first is not null? I need something that is equivalent to this in MongoDB jsonSchema:

last: Joi.string().when('first', { is: null, then: Joi.required().max(10), otherwise:Joi.forbidden() }),

Solution

  • You cannot. Conditional validation if-then-else was introduced in draft-07 a year ago. Mongo uses 7 years old draft-04 of json schema.