Database Reference
In-Depth Information
executes the Add to Cart function, no shopping cart will exist at all. That's why you
use an upsert here. The upsert will construct the document implied by the keys and
values of the query selector and those of the update document. Therefore, the initial
upsert will produce an order document looking like this one:
{
user_id: ObjectId("4c4b1476238d3b4dd5000001"),
state: 'CART',
line_items: [{
_id: ObjectId("4c4b1476238d3b4dd5003981"),
slug: "wheel-barrow-9092",
sku: "9092",
name: "Extra Large Wheel Barrow",
pricing: {
retail: 589700,
sale:
489700
}
}]
}
You then need to issue another targeted update to ensure that the item quantities and
order subtotal are correct:
selector = {user_id: ObjectId("4c4b1476238d3b4dd5000001"),
state: "CART",
'line_items.id': ObjectId("4c4b1476238d3b4dd5003981")}
update = {$inc:
{'line_items.$.qty': 1,
sub_total: cart_item['pricing']['sale']
}
}
db.orders.update(selector, update)
Notice that you use the $inc operator to update the overall subtotal and quantity on
the individual line item. This latter update is facilitated by the positional operator ( $ ),
introduced in the previous subsection. The main reason you need this second update
is to handle the case where the user clicks Add to Cart on an item that's already in the
cart. For this case, the first update won't succeed, but you'll still need to adjust the
quantity and subtotal. Thus, after clicking Add to Cart twice on the wheelbarrow prod-
uct, the cart should look like this:
{
'user_id': ObjectId("4c4b1476238d3b4dd5000001"),
'state' : 'CART',
'line_items': [{
_id: ObjectId("4c4b1476238d3b4dd5003981"),
qty: 2,
slug: "wheel-barrow-9092",
sku: "9092",
name: "Extra Large Wheel Barrow",
Search WWH ::




Custom Search