简体   繁体   中英

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.

Somewhat like this:

在此处输入图片说明

My CategorySchema looks like this

 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. I am new to mongodb, I could'nt find relevant problem-solution on the web, hence seeing help.

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. 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. I hope that helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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