Database Reference
In-Depth Information
The actual function we write to add an item to a cart would resemble the following:
def
def add_item_to_cart ( cart_id , sku , qty , details ):
now = datetime . utcnow ()
# Make sure the cart is still active and add the line item
result = db . cart . update (
{ '_id' : cart_id , 'status' : 'active' },
{ '$set' : { 'last_modified' : now },
'$push' : {
'items' : { 'sku' : sku , 'qty' : qty , 'details' : details } } })
iif not
not result [ 'updatedExisting' ]:
raise
raise CartInactive ()
# Update the inventory
result = db . product . update (
{ '_id' : sku , 'qty' : { '$gte' : qty }},
{ '$inc' : { 'qty' : - qty },
'$push' : {
'carted' : { 'qty' : qty , 'cart_id' : cart_id ,
'timestamp' : now } } })
iif not
not result [ 'updatedExisting' ]:
# Roll back our cart update
db . cart . update (
{ '_id' : cart_id },
{ '$pull' : { 'items' : { 'sku' : sku } } })
raise
raise InadequateInventory ()
Here, we're using the quantity in our update spec to ensure that only a document
with both the right SKU and sufficient inventory can be updated. Once again, we
use safe mode to have the server tell us if anything was updated.
Note that we need to update the carted property as well as qty when modifying
product .
Here, we $pull the just-added item from the cart. Note that $pull means that all
line items for the SKU will be pulled. This is not a problem for us, since we'll in-
troduce another function to modify the quantity of a SKU in the cart.
Since our updates always include _id , and this is a unique and indexed field, no additional
indexes are necessary to make this function perform well.
 
 
 
 
Search WWH ::




Custom Search