Reputation: 3659
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:
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!
Upvotes: 2
Views: 3150
Reputation: 43884
Personally I would implement a materialised paths structure here, it is very easy to update and query using prefixed none case insensitive regexs (which means it will use an index), so an example would look like:
{_id: {}, path: 'about_us/where_are_we'}
This also, as you can see, allows for SEO friendly URLs to hit directly on this tree giving you maximum power. This is particulary helpful in help systems where you like to display a URL like:
/help/how-to-use-my-site
Since how-to-use-my-site
can hit directly on the path or even futher you can house two fields and hit directly on the full text like:
{_id: {}, path: 'about_us/where_are_we', normalised_url: 'where_are_we'}
Of course as the previous answer said you have to know how you wish to access you content but materialised paths are a good start in my opinion.
You can read more on tree structures in Mongo here: http://www.mongodb.org/display/DOCS/Trees+in+MongoDB
Upvotes: 3
Reputation: 1141
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.
Upvotes: 1