Home > other >  How to define a MongoDB Json schema for recursive nested document
How to define a MongoDB Json schema for recursive nested document

Time:09-17

Is there a way to define the JSON Schema for Validation where Document which has a recursive nature in it.

For example : My use case is the comments can have the nested comments in it.

"comments": [
    {
        "user" : "xxx1",
        "message" : "yyyyy1",
        "comments" : [
           {
              "user" : "xxx2",
              "message" : "yyyyy2",
              "comments" : [
                   // and so on
              ]
           }
        ]
    }
]

Not sure how to define a JSON schema for Validation use cases like this.

CodePudding user response:

You can define recursive schemas by putting the recursive bit in a definition and then referencing it with $defs (or definitions, if you are using draft7 or earlier):

{
  "$defs": {
    "comments": {
      "anyOf": [
        {
          ... what does comments look like when it has no more nesting? "type": "string" perhaps?
        },
        {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              .. your other properties...
              "comments": {
                "$ref": "#/$defs/comments"
              }
            }
          }
        }
      ]
    }
  },
  ... the rest of your schema, which will use a "$ref": "#/$defs/comments" somewhere...
}

There is also an example of this at https://json-schema.org/understanding-json-schema/structuring.html#recursion.

CodePudding user response:

If you are using NodeJS (Express), you can do it like this using Mongoose:

var commentSchema = new Schema();
commentSchema.add({
  user: { type: mongoose.Schema.Types.ObjectId, ref: 'USERS', required: true },
  message: { type: String,  required: true },
  comments: [ commentSchema ]
})
  • Related