I am trying to learn Mongodb and decided to build a simple blog application using Zend Framework and Mongodb (using Shanty for ZF).
I have the following document for Post
class App_Model_Post extends Shanty_Mongo_Document
{
protected static $_db = 'blog';
protected static $_collection = 'posts';
protected static $_requirements = array(
'Title' => 'Required',
'Content' => 'Required',
'CreatedOn' => 'Required',
'Author' => array('Document:App_Model_User', 'Required', 'AsReference'),
'Slug' => 'Required',
);
public function preSave()
{
$title = $this->Title;
$this->Slug = strtolower($title);
}
}
Document for Comment:
class App_Model_Comment extends Shanty_Mongo_Document
{
protected static $_db = 'blog';
protected static $_collection = 'comments';
protected static $_requirements = array(
'Content' => 'Required',
'Author' => array('Required', 'Document:App_Model_User', 'AsReference'),
'Post' => array('Required', 'Document:App_Model_Post'),
);
}
In my controller I do the following to get the Post and Comments for this Post:
public function viewAction()
{
$slug = $this->_getParam('id');
$post = App_Model_Post::one(array('Slug' => $slug));
$this->view->post = $post;
$this->view->title = 'Post Title : ' . $post->Title;
$comments = App_Model_Comment::all(array('Post.Slug' => $post->Slug))->skip(0)->limit(10);
$this->view->comments = $comments;
}
I wonder if this is a good way to accomplish this. Is it good practice to reference to Post in the Comment or should I inject Comment documents to Post document?
1 Answer 1
The correct answer depends on a few application design decisions.
Reasons why you should embed Comments in Posts:
- You have a limit on the number of comments that can be on a post
- The comment limit is relatively small (mongodb docs have a hard limit of 4mb but you don't want to be pulling 4mb data down at once, so your limit should take this into consideration)
- You need access to all comments on a post when you load a post
Reasons why you should reference Posts from Comments:
- You want to have unlimited comments on a post
- You're ok with loading the post first then going back to the database every time you need comments
- You want to fetch comments without posts
I offer a combined approach. Store comments in their own collection but store a total comments counter and possibly recent comments against the post. This way you can have unlimited comments but still have access to important information when listing posts without having to go back to the database.
I hope this helps