node.jsmongodbexpressschemaajv

AJV - additionalProperties: false but with exceptions


I am using ajv to validate my mongodb schemas.

{
  type: "object",
  properties: { goal: { type: "string" }, cost: { type: "number" } },
  required: ["goal", "cost"],
  additionalProperties: false,
}

The above is the ajv schema for a document in my collection. The property additionalProperties: false is configured, so no additional properties are allowed.

The question is, how do I specify a set of exceptional additional properties that are allowed?


Solution

  • Any property in your schema that is not specified as required is basically optional: it will be validated when exists, but will be ignored if missing when data is being validated.

    See the example below of validating object with "optional" maybeValue property:

    const Ajv = require("ajv");
    const ajv = new Ajv();
    
    const schema = {
      type: "object",
      properties: { 
        goal: { type: "string" },
        cost: { type: "number" }, 
        maybeValue: { type: "string" },
      },
      required: ["goal", "cost"], // maybeValue is "optional"
      additionalProperties: false,
    };
    
    const validate = ajv.compile(schema);
    
    const valid = {
      goal: 'win',
      cost: 10,
    };
    
    // this is a valid schema also maybeValue is missing since it is not required
    validate(valid);
    
    const notValid = {
      goal: 'win',
      cost: 10,
      maybeValue: 10
    };
    
    // this is a not a valid schema since maybeValue is not a string
    validate(notValid);