如何在MongoDB Schema中设置支持无限嵌套的递归字段?
实现children数组无限嵌套的方案
要让children支持无限嵌套自身元素,核心就是递归定义元素结构——让每个子元素跟父元素结构完全一致,都能带自己的children字段。
不同场景的实现方式
不管你是用Mongoose、Vue Prop验证还是普通JS对象定义,思路都是先搞一个能递归引用的元素结构:
1. 普通JS对象结构(通用场景)
直接把children字段加到元素结构里,让它的类型是自身的数组:
// 定义基础元素结构,自带children实现递归 const ElementStructure = { element: { type: String, required: [true, 'ELEMENT IS REQUIRED'] }, attributes: { type: Object }, children: { type: Array, default: [], // 每个子项都遵循ElementStructure的规则 of: ElementStructure } } // 根组件的children直接用这个结构的数组 const ComponentStructure = { // 根组件其他字段... children: { type: Array, default: [], of: ElementStructure } }
2. 用Mongoose(MongoDB场景)
Mongoose需要先注册模型再自引用,用函数式或者直接指定模型名就行:
const mongoose = require('mongoose'); // 定义元素Schema,children引用自身模型 const ElementSchema = new mongoose.Schema({ element: { type: String, required: [true, 'ELEMENT IS REQUIRED'] }, attributes: mongoose.Schema.Types.Mixed, children: [{ type: 'Element' }] // 这里用模型名自引用 }); // 先注册模型,不然children找不到引用 mongoose.model('Element', ElementSchema); // 根组件的Schema const ComponentSchema = new mongoose.Schema({ // 根组件其他字段... children: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Element' }] });
3. Vue组件Prop验证(前端场景)
在Vue的props里可以写个递归的验证函数,确保每一层都符合规则:
export default { props: { children: { type: Array, default: () => [], validator: (value) => { // 递归验证单个元素 const checkElement = (el) => { if (typeof el.element !== 'string') return false; if (el.attributes && typeof el.attributes !== 'object') return false; // 如果有children,挨个递归验证 if (el.children && Array.isArray(el.children)) { return el.children.every(child => checkElement(child)); } return true; }; return value.every(el => checkElement(el)); } } } }
核心逻辑
每个子元素都跟父元素结构完全一样,都包含element、attributes和children,这样就能无限嵌套下去。验证的时候要么靠Schema自引用,要么写递归函数检查每一层结构。
内容的提问来源于stack exchange,提问作者user22362540
相关产品推荐
相关产品推荐

