Database Reference
In-Depth Information
Schema
Ourschemaforthisportionofthesystemconsistsoftwocollections:
product
and
cart
.Let's
consider
product
first. This collection contains one document for each item a user can place
in their cart, called a “stock-keeping unit” or SKU. The simplest approach is to simply use a
SKU number as the
_id
and keep a
quantity
counter for each item. We'll add in a
details
field for any item details you wish to display to the user as they're browsing the store:
{
_id
:
'00e8da9b'
,
qty
:
16
,
details
:
... }
It turns out to be useful to augment this schema with a list of shopping carts containing the
particular SKU. We do this because we're going to use
product
as the definitive
collection of
record
for our system. This means that if there is ever a case where
cart
and
product
contain
inconsistent data,
product
is the collection that “wins.” Since MongoDB does not support
multidocument transactions, it's important to have a method of “cleaning up” when two col-
lections become inconsistent, and keeping a
carted
property in
product
provides that avenue
here:
{
_id
:
'00e8da9b'
,
qty
:
16
,
carted
:
[
{
qty
:
1
,
cart_id
:
42
,
timestamp
:
ISODate
(
"2012-03-09T20:55:36Z"
), },
{
qty
:
2
,
cart_id
:
43
,
timestamp
:
ISODate
(
"2012-03-09T21:55:36Z"
) }
]
}
In this case, the inventory shows that we actually have 16 available items, but there are also
two carts that have not yet completed checkout, which have one and two items in them, re-
spectively.
Our
cart
collection, then, would contain an
_id
,
state
,
last_modified
date to handle ex-
piration, and a list of items and quantities:
{
_id
:
42
,
last_modified
:
ISODate
(
"2012-03-09T20:55:36Z"
),
status
:
'active'
,
items
:
[