Mongo DB - sub-collections?

I'm really new to MongoDb and am using it with nodeJS and the native node mongodb driver. I am having doubts about implementation. I hope you can help me: I have this "schema", where db.pages holds the config for each section of my website:

db.pages = [
   {name: 'contacts', settings:{...}},
   {name: 'blog', settings:{...}, posts: "blogPosts"},
   {name: 'media', settings: {...}, posts: "mediaPosts"}
]

db.blogPosts = [
  {title: 'post1', date: '2011-10-22', author:'me', content: '...'},
  {title: 'post2', date: '2011-11-22', author:'me', content: '...'},
  {...............................................................}
];

What I'm doing here is, in each page, I define if I have a posts collection and, in node, when I load the page, I check if page.posts is defined and, if so, load the appropriate collection.

Maybe I'm wrong, but this is looking too much as a relational thing so, my idea, would be to put the content of blogPosts directly as the value for the prop posts of the pages collection, like so:

db.pages = [
       {name: 'contacts', settings:{...}},
       { name: 'blog', 
         settings:{...}, 
         posts: [
            {title: 'post1', date: '2011-10-22', author:'me', content: '...'},
            {title: 'post2', date: '2011-11-22', author:'me', content: '...'},
            {...............................................................}
         ]
       },
       {name: 'media', settings: {...}, posts: [...]}
    ]

I really think this makes much more sense, in a NoSQL environment, but I might be wrong. The problem I am having is that using the latter configuration, I can't seem to make nodejs treat the posts field as a mongo collection.

I hope this makes any sense to you and, if so, what I need to know is:

  1. Am I right or wrong to think the second way is the right way?
  2. How can I use node to read that 'sub-collection' as collection so I can apply a cursor and use find(), sort(), limit(), skip(), etc, on it...

Upvotes: 12

Views: 12989

Answers (1)

Samarth Bhargava
Samarth Bhargava

Reputation: 4228

First approach is better. Second approach has multiple drawbacks:

  1. Each document has a size limit of 16MB. You will hit that limit and will not be able to add more blog posts
  2. You cannot query and fetch individual blog posts from the disk as its all in one big document
  3. if you apply this principle, then you will put all the comments also in the same pages document, further complicating it and will loose lot of flexibility

Upvotes: 12

Related Questions