【问题标题】:How to define a MongoDB Json schema for recursive nested document如何为递归嵌套文档定义 MongoDB Json 模式
【发布时间】:2021-10-30 18:00:51
【问题描述】:

有没有办法定义 JSON Schema for Validation where Document 具有递归性质。

例如:我的用例是 cmets 可以包含嵌套的 cmets。

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

不确定如何为此类验证用例定义 JSON 架构。

【问题讨论】:

    标签: mongodb validation mongoose jsonschema


    【解决方案1】:

    如果您使用的是 NodeJS (Express),您可以使用 Mongoose 这样做:

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

    【讨论】:

    • 这似乎假定了一种特定的实现和编程语言(您没有指定)。它本身不是一个有效的 JSON Schema,不能移植到其他实现中。
    【解决方案2】:

    您可以通过将递归位放入定义中然后使用$defs(或definitions,如果您使用的是draft7或更早版本)引用它来定义递归模式:

    {
      "$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...
    }
    

    https://json-schema.org/understanding-json-schema/structuring.html#recursion 也有一个例子。

    【讨论】:

    猜你喜欢
    • 2011-11-10
    • 2015-11-27
    • 1970-01-01
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 2018-01-02
    相关资源
    最近更新 更多