Database Reference
In-Depth Information
4.2.3
Reviews
We'll close the sample data model with product reviews. Relationally speaking, each
product has many reviews. Here, that relationship is encoded using an object ID refer-
ence, review_id , which you can see in this sample review document.
Listing 4.5
A document representing a product review
{ _id: new ObjectId("4c4b1476238d3b4dd5000041"),
product_id: new ObjectId("4c4b1476238d3b4dd5003981"),
date: new Date(2010, 5, 7),
title: "Amazing",
text: "Has a squeaky wheel, but still a darn good wheel barrow.",
rating: 4,
user_id: new ObjectId("4c4b1476238d3b4dd5000041"),
username: "dgreenthumb",
helpful_votes: 3,
voter_ids: [ new ObjectId("4c4b1476238d3b4dd5000041"),
new ObjectId("7a4f0376238d3b4dd5000003"),
new ObjectId("92c21476238d3b4dd5000032")
]
}
Most of the remaining attributes are self-explanatory. You store the review's date,
title, and text; the rating provided by the user; and the user's ID . But it may come as
a surprise that you store the username as well. After all, if this were an RDBMS , you'd
be able to pull in the username with a join on the users table. Since you don't have
the join option with MongoDB, you can proceed in one of two ways: either query
against the user collection for each review or accept some denormalization. Issuing a
query for every review might be unnecessarily costly when the attribute being que-
ried (the username) is extremely unlikely to change. To be sure, you could go the
normalized route and display all reviews in just two MongoDB queries. But here
you're designing a schema for the common case. This does mean that a username
update is more expensive, since a username will need to change in every place that
it appears, but again, that happens infrequently enough to justify this as a reason-
able design choice.
Also noteworthy is the decision to store votes in the review document itself. It's
common for users to be able to vote on reviews. Here, you store the object ID of each
voting user in an array of voter IDs. This allows you to prevent users from voting on a
review more than once, and it also gives you the ability to query for all the reviews a
user has voted on. Note also that you cache the total number of helpful votes, which
among other things allows you to sort reviews based on helpfulness.
With that, we've covered a basic e-commerce data model. If this is your first time
looking at a MongoDB data model, then contemplating the utility of this model may
require a leap of faith. Rest assured that the mechanics of all of this—from adding
votes uniquely, to modifying orders, to querying products intelligently—will be
 
Search WWH ::




Custom Search