关于使用Mongoose进行无限嵌套子文件的问题。
发布于 9 年前 作者 EdwardStudy 3641 次浏览 最后一次编辑是 8 年前 来自 问答

最近一直在用Mongoose进行数据库交互,但出现了一个问题。 我原本是这样使用Schema

var fatherSchema = new Schema{
	//一些数据结构
	children: [chilldrenSchema]
};
var chilldrenSchema = new Schema{
	//一些数据结构
	children: [chilldrenSchema]
};

数据库正常存储好father(首先children是无值得)后,也能正常保存children(使用查询回调中返回father,添加father.children=一个json,最后再使用.save),无法保存father.children[0].newChildren。(也是使用的是find-save,) mogoose的issue里说 是Schema定义顺序的问题,也就是childrenSchema要放在fatherSchema前面,若childrenSchema还嵌套了一个,就需要在在childrenShema前面定义好secondChildrenSchema。 我丑陋的解决方法就是这样从后往前依次声明 var ninethChildrenSchema = {} ;… var secondChildrenShema = {}; 那么问题来了,我的这些孩子的层级在实际应用中是不确定的(可能特别多也可能只有3-4层),有什么优美的方法可以动态声明Schema吗?

1 回复

具体细节我写在 博客第二段了。

回到顶部