Multiple JSON Schemas with *oneOf*

Hi,

The quiz for the Schema Validation lecture has the following question:

Problem:

Which of the following can be validated through schema validation in MongoDB?

One of the answers is:

A document has either one of two strict shapes.

There is a construct in JSON Schema called oneOf that let you specify two sub-schemas.

Use this technique for verifying different shapes of documents, including checking a specific shape for a document version.

Could someone please clarify why a document has either one of two strict shapes?

Thanks.

Hi @Ilan_Cohen,

Apology for the late response. We appreciate your patience.

Here oneOf is a keyword construct in the JSON Schema, which is used to provide an array of criteria where, if exactly one of them is valid, the whole block is valid.

For example,

{
  "title": "JSON Schema",
  "type": "object",
  "properties": {
    // define properties here
  },
  "oneOf":[
    {
      "required": [
        "email",
        "password"
      ]
    },
    {
      "required": [
        "username",
        "password"
      ]
    }
  ]
}

As per the exampe above, objects having ( "email" AND "password" ) OR ( "username" AND "password" ) attributes are considered valid.

However, an object having "email" , "username" and "password" attributes would fail .

Similar to "oneOf", there are two more keywords "anyOf" and "allOf" and by using them we would consider objects valid when they match one or more or all of the specified required attributes, respectively.

Please feel free to reach out if you have any additional questions.

Good Luck… :slightly_smiling_face:

Regards,
Kushagra

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.