skip to Main Content

Can a field validation in MongoDB collection contain string and null both as validation types.

{
  "$jsonSchema": {
    "bsonType": "object",
    "title": "Validations",
    "properties": {
      "t1": {
        "bsonType": "string",
        "description": "label field is required with min. 1 character in length"
      }
    }
  }
}

Can we specify field t1 be either a null or string type?

2

Answers


  1. Just use { "bsonType": [ "null", "string" ] } like the official doc did.

    {
      $jsonSchema: {
        properties: {
          t1: {
            bsonType: [
              'null',
              'string'
            ]
          }
        },
        description: 'label field is required with min. 1 character in length'
      }
    }
    
    Login or Signup to reply.
  2. I think just add ‘null’ into bsonType. We also could combine with another validation (example with minLength). It will be validated if the value is not null

    {
      "$jsonSchema": {
        "bsonType": "object",
        "title": "Validations",
        "properties": {
          "t1": {
            "bsonType": ["string", "null"],
            "description": "t1 field can be a string with at least [number] character or null",
            "minLength": [number]
          }
        },
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search