Mongo Json Schema Validator AnyOf not working

后端 未结 1 1367
感情败类
感情败类 2021-01-22 18:19

I have created the a collection with the below validation:

{
  $jsonSchema: {
    bsonType: \'object\',
    additionalProperties: false,
    properties: {
               


        
相关标签:
1条回答
  • 2021-01-22 19:01

    {test:"123"} fails validation because it doesn't conform to any of the schemas in anyOf, which need test1 or test2 as the only key.

    anyOf applies each subschema to your instance, and asserts valid if at least one of the subschemas passes validation.

    {test1: "123" } fails because the root schemas additionalProperties: false prevents any keys in your object not defined in the SAME schema object properties or patternProperties.

    The solution is to have some duplication.

    In THIS example (link is for in browser testing but draft-7 only), I've added root properties test1 and test2. This will allow data where you have a key of test1 or test2 to pass, but given I don't know your requirements, I can't tell you how to modify the schema to allow an object with a key of test to pass (as each of the anyOf subschemas prevent it).

    {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "_id": {},
        "test": {},
        "test1": {},
        "test2": {}
      },
      "anyOf": [
        {
          "type": "object",
          "properties": {
            "test1": {}
          },
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "test2": {}
          },
          "additionalProperties": false
        }
      ]
    }
    

    If your intent is to check that one of the things you are inserting has test1 or test2, then I'm afraid JSON Schema cannot help you. JSON Schema in the context of Mongo can only check each item individually, and is not afforded the ability to validate a collection of potentially inserted records.

    In the above example schema, I've removed type checking because that is not relevant to this question, and bsonType differs from JSON Schema type anyway.

    0 讨论(0)
提交回复
热议问题