Forum Discussion

SSchandrakant's avatar
SSchandrakant
New Member
2 years ago

oneOf only validates the schema but does not add missing field with default values.

I have defined this schema that selects a schema based on animal field and then validates the request body depending upon selected animal schema.
but this does not append the field with default values.
```

{
  type: 'object',
  discriminator: {
    propertyName: 'animal',
    mapping: {
      cat: '#/oneOf/0',
      dog: '#/oneOf/1'
    }
  },
  oneOf: [
    {
      type: 'object',
      required: ['name', 'age'],
      properties: {
        animal: {
          type: 'string',
          enum: ['cat']
        },
        isLazy: {
          type: 'boolean',
          default: true
        },
        name: {
          type: 'string'
        },
        age: {
          type: 'integer'
        }
      },
    },
    {
      type: 'object',
      required: ['breed', 'weight'],
      properties: {
        animal: {
          type: 'string',
          enum: ['dog']
        },
        isFriendly: {
          type: 'boolean',
          default: true
        },
        breed: {
          type: 'string'
        },
        weight: {
          type: 'number'
        }
      },
    }
  ],
}
here if i upload a request:
```
{
"animal": "cat",
"name": "Whiskers",
"age": 5
}

```
in this case isLazy field should get added with default value true to the req.body received by API.
i.e
```
{
"animal": "cat",
"isLazy": true,
"name": "Whiskers",
"age": 5
}
```
Can someone confirm if oneOf or discriminator only validates the request or does it also add default values like a normal schema.
i am using openapi: version 3.0.3 and express-openapi.


  • Hi SSchandrakant ,

     

    Your example looks fine from a specification point of view, for the implementation specific questions (i.e., express-openapi) you'll need to reach out to that project specifically. Perhaps via GitHub.

     

    Hope that helps!