简体   繁体   English

MongoDB查找并插入子文档树(猫鼬)中

[英]MongoDB find and insert in a tree of subdocument (mongoose)

Creating TREE of categories and subcategories 创建类别和子类别的树

Hello guys Am creating a tree of categories for my application. 大家好我正在为我的应用程序创建类别树 There is no limit (infinite) to the depth of subcategories that can be created. 可以创建的子类别的深度no limit (infinite)

Somewhat like this: 有点像这样:

在此处输入图片说明

My CategorySchema looks like this 我的CategorySchema看起来像这样

 schema: {  
        _id : String,
        name: String,
        children: []  // will contain subcats in form of {_id:String,  name: String, children: []}
 }

MY PROBLEM 我的问题

I want a dynamic solution/mongodb-query/mongoose-query to CREATE the tree of categories. 我想要一个动态解决方案/ mongodb-query / mongoose-query 创建类别树。 I am new to mongodb, I could'nt find relevant problem-solution on the web, hence seeing help. 我是mongodb的新手,我无法在网络上找到相关的问题解决方案,因此获得了帮助。

Have already spent quite a lot of time trying by myself. 我已经花费了很多时间尝试。 Please help me with any (but should be efficient) solution to my poblem. 请为我的问题提供任何(但应该是有效的)解决方案,以帮助我。

Thanks in advance 提前致谢

you should use population with mongoose, here is a link to their API's that explains how population works in Mongoose. 您应该将人口与猫鼬一起使用,这是指向其API的链接 ,该API解释了人口在猫鼬中的工作方式。 Also when you say dynamic, I'm assuming you want to build a query that rebuilds the entire tree structure before returning it to you since you specified that there is no limit to the depth of the tree. 同样,当您说动态时,我假设您想构建一个查询,该查询在将整个树结构返回给您之前会重建整个树结构,因为您指定了树的深度没有限制。 In that case you might be tempted to use a recursive solution, but I would advice against doing that for reasons that are discussed here . 在这种情况下,您可能会想使用递归解决方案,但出于此处讨论的原因,我建议您不要这样做。 I think that a solution to your problem can be found here . 我认为可以在这里找到解决您问题的方法。 This solution uses promises recursively and as you'll see the poster say, it's not very performant for large N. On the whole your question is rather similar to the one asked here and I think that reading the entire thing will really help you out. 该解决方案递归地使用了promise,正如您将看到张贴者说的那样,它对于大的N而言并不是很好的表现。总的来说,您的问题与此处提出的问题非常相似,我认为阅读整本书确实可以帮助您。 I hope that helped. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM