You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何为CMS深层嵌套DOM结构文档添加递归JSON Schema验证?

问题

我正在构建一个CMS项目,需要将DOM结构存储到MongoDB集合中,目前已经实现了结构存储与DOM还原功能,现在要为Schema添加验证规则。我想知道能不能设置递归验证方式,遍历整个JSON对象,对所有层级的children键值对执行相同验证?因为无法预知用户嵌套HTML元素的深度,现有验证只支持浅层children验证,附上示例文档及当前验证代码。

示例文档

{"tag": "div","text": "here is a div","children": [{"tag": "h1","text": "Hello"},{"tag": "h2","text": "world","children": [{"tag": "h3","text": "this becomes deep...","children": [{"tag": "h4","text": "...and even deeper..."}]}]}]}

当前验证代码

{
    $jsonSchema: {
        required: ['tag'],
        properties: {
            tag: {
                bsonType: 'string',
            },
            text: {
                bsonType: ['string','int','double'],
            },
            children: {
                bsonType: 'array',
                items: {
                    bsonType: 'object',
                    required: ['tag'],
                    properties: {
                        tag: {
                            bsonType: 'string',
                        },
                        text: {
                            bsonType: ['string','int','double'],
                        }
                    }
                }
            }
        }
    }
}

注:为简化展示,上述为最小化验证示例,实际验证包含更多规则。


解决方案

MongoDB的JSON Schema支持通过$ref和definitions字段实现递归验证,刚好能解决你这种嵌套层级不确定的DOM结构验证需求。

核心思路是:

  • 在definitions中定义一个可复用的节点验证规则,这个规则里包含自身的递归引用(即children数组的items引用这个节点规则)
  • 根节点直接引用这个定义好的规则

修改后的验证代码如下:

{
    $jsonSchema: {
        $ref: '#/definitions/domNode'
    },
    definitions: {
        domNode: {
            bsonType: 'object',
            required: ['tag'],
            properties: {
                tag: {
                    bsonType: 'string'
                },
                text: {
                    bsonType: ['string', 'int', 'double']
                },
                children: {
                    bsonType: 'array',
                    items: {
                        $ref: '#/definitions/domNode'
                    }
                }
            }
        }
    }
}

代码说明

  1. definitions里的domNode定义了单个DOM节点的验证规则,包含必填的tag(字符串类型)、可选的text(字符串/数字类型),以及children数组
  2. children数组的items通过$ref: '#/definitions/domNode'递归引用同一个节点规则,不管嵌套多少层,所有层级的子节点都会遵循相同的验证逻辑
  3. 根节点直接用$ref指向这个定义好的规则,确保整个文档从根到所有子节点都符合验证要求

这种方式完全适配任意深度的嵌套结构,后续如果需要扩展验证规则(比如增加attributes字段验证),只需要修改domNode里的规则即可,所有层级都会自动应用新规则。

内容的提问来源于stack exchange,提问作者blabbath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 04:54:12