Databases Reference
In-Depth Information
Designing the News Aggregator
We'll be creating a simple news aggregator, where users can submit links to interesting
stories and other users can vote and comment on them. We will just be covering two
aspects of it: creating a tree of comments and handling votes.
To store the submissions and comments, we need only a single collection, posts . The
initial posts linking to some article will look something like the following:
{
"_id" : ObjectId(),
"title" : "A Witty Title",
"url" : "http://www.example.com",
"date" : new Date(),
"votes" : 0,
"author" : {
"name" : "joe",
"_id" : ObjectId(),
}
}
The comments will be almost identical, but they need a "content" key instead of a
"url" key.
Trees of Comments
There are several different ways to represent a tree in MongoDB; the choice of which
representation to use depends on the types of query being performed.
We'll be storing an array of ancestors tree: each node will contain an array of its parent,
grandparent, and so on. So, if we had the following comment structure:
original link
|- comment 1
| |- comment 3 (reply to comment 1)
| |- comment 4 (reply to comment 1)
| |- comment 5 (reply to comment 4)
|- comment 2
| |- comment 6 (reply to comment 2)
then comment 5's array of ancestors would contain the original link's _id , comment
1's _id , and comment 4's _id . Comment 2's ancestors would be the original link's
_id and comment 2's _id . This allows us to easily search for “all comments for link
X" or “the subtree of comment 2's replies.”
This method of storing comments assumes that we are going to have a lot of them and
that we might be interested in seeing just parts of a comment thread. If we knew that
we always wanted to display all of the comments and there weren't going to be
thousands, we could store the entire tree of comments as an embedded document in
the submitted link's document.
 
Search WWH ::




Custom Search