I’m trying to do something usually simple with SQL (with foreign key in the same table for example) (it may be as easy with MongoDB, I just don’t know yet) which is to build a recursive data structure.
For this example, I’ll talk about Pages in a Website. I’d like to make a multiple level page structure. So there could be:
- Home
- Our Products
- Product 1
- Product 2
- About us
- Where are we?
- Contact us
Let’s say pages would have a title and a content.
I need to know what’s the best way to do this, and also how I could build a sitemap based on that data structure (page that shows every page from every level).
I’m building a node.js app with MongoDB for this case.
EDIT: Wouldn’t it work by simply referencing a parent page in each page? Pages would be like { title: 'test', content: 'hello world', parentPage: ObjectID(parent page) }
Thanks for the help!
You will need to know how you want to access to your data.
The last time I was using a tree structure I implemented this (I took inspiration from various sources) in Ruby, it stores an _id path and the complete uri (slugified page titles), it is a pain to handle structures like this.
On the other side, you can create a collection documents (roots) and embedded documents (branches and leaves). It is more simple to handle but you will have to get the whole tree when querying, and you can query the inner documents only if you know how deep it is.
From my past experiences all the work to support a tree structure is not worth the candle (unless it is a requirement), most users will create a loose structure based more on tags than fixed categories.