Database Reference
In-Depth Information
db.orders.findAndModify({
query: {user_id: ObjectId("4c4b1476238d3b4dd5000001"),
state: "AUTHORIZING" },
update: {"$set":
{"state": "PRE-SHIPPING"},
"authorization": auth}
})
It's important to be aware of the MongoDB features that facilitate this transactional
process. There's the ability to modify any one document atomically. There's the guar-
antee of consistent reads along a single connection. And finally, there's the document
structure itself, which allows these operations to fit within the single-document atom-
icity that MongoDB provides. In this case, that structure allows you to fit line items,
products, pricing, and user ownership into the same document, ensuring that you
only ever need to operate on that one document to advance the sale.
This ought to strike you as impressive. But it may lead you to wonder, as it did me,
whether any multi-object transaction-like behavior can be implemented with MongoDB.
The answer is a cautious affirmative and can be demonstrated by looking into another
e-commerce centerpiece: inventory management.
6.3.2
Inventory management
Not every e-commerce site needs strict inventory management. Most commodity items
can be replenished in a reasonable enough time to allow any order to go through
regardless of the actual number of items on hand. In cases like these, managing inven-
tory is easily handled by managing expectations; as soon as only a few items remain in
stock, adjust the shipping estimates.
One-of-a-kind items present a different challenge. Imagine you're selling concert
tickets with assigned seats or handmade works of art. These products can't be hedged;
users will always need a guarantee that they can purchase the products they've
selected. Here I'll present a possible solution to this problem using MongoDB. This
will further illustrate the creative possibilities in the findAndModify command and the
judicious use of the document model. It'll also show how to implement transactional
semantics across multiple documents.
The way you model inventory can be best understood by thinking about a real
store. If you're in a gardening store, you can see and feel the physical inventory; doz-
ens of shovels, rakes, and clippers may line the aisles. If you take a shovel and place it
in your cart, that's one less shovel available for the other customers. As a corollary, no
two customers can have the same shovel in their shopping carts at the same time. You
can use this simple principle to model inventory. For every physical piece of inven-
tory in your warehouse, you store a corresponding document in an inventory collec-
tion. If there are 10 shovels in the warehouse, there are 10 shovel documents in the
database. Each inventory item is linked to a product by sku , and each of these items
can be in one of four states: AVAILABLE (0), IN_CART (1), PRE_ORDER (2), or
PURCHASED (3).
Search WWH ::




Custom Search