Database Reference
In-Depth Information
_id: new ObjectId("9a9fb1476238d3b4dd5000001"),
slug: "outdoors"
}
],
parent_id: new ObjectId("9a9fb1476238d3b4dd5000001"),
name: "Gardening Tools",
description: "Gardening gadgets galore!",
}
If you go back to the product document and look carefully at the object ID s in its
category_ids field, you'll see that the product is related to the Gardening Tools cate-
gory just shown. Having the category_ids array key in the product document enables
all the kinds of queries you might issue on a many-to-many relationship. For instance,
to query for all products in the Gardening Tools category, the code is simple:
db.products.find({category_ids => category['_id']})
To q u e r y f o r a l l c a t e g o r i e s f r o m a g i v e n p r o d u c t , y o u u s e t h e $in operator. This is
analogous to SQL 's IN directive:
db.categories.find({_id: {$in: product['category_ids']}})
With the many-to-many relationship described, I'll say a few words about the category
document itself. You'll notice the standard _id , slug , name , and description fields.
These are straightforward, but the array of parent documents may not be. Why are
you redundantly storing such a large percentage of each of the document's ancestor
categories? The fact is that categories are always conceived of as a hierarchy, and the
ways of representing such a hierarchy in a database are many. 2 The strategy you
choose is always dependent on the needs of the application. In this case, because
MongoDB doesn't support joins, we've elected to denormalize the parent category
names in each child document. This way, when querying for the Gardening Products
category, there's no need to perform additional queries to get the names and URL s of
the parent categories, Outdoors and Home.
Some developers would consider this level of denormalization unacceptable.
There are other options for representing a tree, and one of these is discussed in
appendix B. But for the moment, try to be open to the possibility that what best deter-
mine the schema are the demands of the application, and not necessarily the dictates
of theory. When you see more examples of querying and updating this structure in
the next two chapters, the rationale will become clearer.
4.2.2
Users and orders
Looking at how you model users and orders illustrates another common relationship:
one-to-many. That is, every user has many orders. In an RDBMS , you'd use a foreign
key in your orders table; here, the convention is similar. Examine the following listing:
2
Two such methods, the adjacency list and the nested set, are presented in this MySQL developer article:
http://mng.bz/83w4.
 
Search WWH ::




Custom Search