Databases Reference
In-Depth Information
If the information about a product is updated, all of the documents referencing
this product will “change,” as these documents merely point to the definitive
document.
Normalization gives us slower reads and a consistent view across all orders; mul-
tiple documents can atomically change (as only the reference document is actually
changing).
Denormalized schema
A product (same as previous):
{
"_id" :
productId
,
"name" :
name
,
"price" :
price
,
"desc" :
description
}
An order:
{
"_id" :
orderId
,
"user" :
userInfo
,
"items" : [
{
"_id" :
productId1
,
"name" :
name1
,
"price" :
price1
},
{
"_id" :
productId2
,
"name" :
name2
,
"price" :
price2
},
{
"_id" :
productId3
,
"name" :
name3
,
"price" :
price3
}
]
}
We store the product information as an embedded document in the order. Then,
when we display an order, we only need to do a single query.
If the information about a product is updated and we want the change to be propa-
gated to the orders, we must update every cart separately.
Denormalization gives us faster reads and a less consistent view across all orders;
product details cannot be changed atomically across multiple documents.
So, given these options, how do you decide whether to normalize or denormalize?