java mongo json schema validation

Viewed 628

I would like to know if mongock supports synthax such as:

 "allOf": [{ "$ref": "/schema/base" }]

when it build the validation during the collection creation or if you know a library that can be used to "merge" all the references in a unique big json schema that can be given as input to the Document used for the validation.

The code I'm using to validate a collection is:

    String jsonString = readJsonFile(fileName);

    Document doc = Document.parse(jsonString);

    ValidationOptions validationOptions = new ValidationOptions();
    validationOptions.validator(doc);
    validationOptions.validationAction(ValidationAction.ERROR);
    validationOptions.validationLevel(ValidationLevel.STRICT);
    CreateCollectionOptions cco = new CreateCollectionOptions();
    cco.validationOptions(validationOptions);

As you can see for now I'm simply reading the json schema from the file and parse it with the Document object.

I would like to keep the json schema simpler as possible to be human readable and I have objects that extends others, so it would be easier to have separated json schema files to represent the super objects.

I'm using java 1.13 and spring boot 2.4.2.

2 Answers

Mongock currently doesn't provide a schema validation mechanism. However, the team is considering to add as a patch after version 5 is released

As this may be a helpful information on this topic - it's possible to add validation rules when creating the collection using Mongock. What works for me:

mongoTemplate.createCollection(FileInfo.class, CollectionOptions.empty()
        .validator(Validator.schema(MongoJsonSchema.builder()
                .required("fileStatus", "path")
                .build())));

Will make this two fields required.

Related