How to build a recursive structure with MongoDB

两盒软妹~` 提交于 2020-01-05 07:15:10

问题


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!


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/11808460/how-to-build-a-recursive-structure-with-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!