The first thing to realize is that mongoDB collections can be changed on the fly. They are squishy like that. So even though the previous test posts I had added did not have comment fields this wasn't a deal breaker and I didn't have to start over or delete anything.
Step 1) Create a new php page to enter comments on. I called it commentPoster.php
This page is passed 2 things - 1) how many comments a blog post currently has
2) the obj id of the blog post so the page can look up the item
Step 2) Modify the blog page so that the blog entries show a link under them stating how many
comments there are for the post. The link takes the reader to the new commenter page.
Knowing how many comments existed already was key. This allows the page to put a new comment into the new comments array in the proper place.
Here is the code.
Notice how I created the comment object with its own comments array inside. This way people can comment on other comments. This will look something like this:
![]() |
Reddit Comments |
So you can see that it adds the number in as part of the structure. So instead of comments[1], comments[2], etc... it looks like the associative array version and is putting in the numbers themselves.
To get the number of comments link on the blog post link I did this:
After I pulled up the blog post from mongoDB I checked to see if the object had comments (all my early posts didn't). If if does have a comment field than I get the get the comments array out and use the php method sizeof to get the number of comments out.
$numComments = 0;
if (array_key_exists('comments', $obj)) {
$array = $obj['comments'];
$numComments = sizeof($array);
}
Finally it was just a simple matter of adding the new $numComments object to the link to the commentPoster.php page.
<a href="commentPoster.php?id='.$obj['_id'].'&numComments='.$numComments.'">'.$numComments.' comments</a>
And that was that.
Until Next Time
Cheers,
TheSortedProgrammer