简体   繁体   中英

java mongo json schema validation

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM