Database Reference
In-Depth Information
pricing: {
retail: 589700,
sale:
489700
}
}],
subtotal: 979400
}
There are now two wheelbarrows in the cart, and the subtotal reflects that.
There are still more operations you'll need to fully implement a shopping cart.
Most of these, such as removing an item from the cart or clearing a cart altogether,
can be implemented with one or more targeted updates. If that's not obvious, the
upcoming subsection describing each query operator should make it clear. As for the
actual order processing, that can be handled by advancing the order document
through a series of states and applying each state's processing logic. We'll demonstrate
this in the next section, where I explain atomic document processing and the find-
AndModify command.
6.3
Atomic document processing
One tool you won't want to do without is MongoDB's findAndModify command. 5 This
command allows you to atomically update a document and return it in the same
round trip. This is a big deal because of what it enables. For instance, you can use
findAndModify to build job queues and state machines. You can then use these primi-
tive constructs to implement basic transactional semantics, which greatly expand the
range of applications you can build using MongoDB. With these transaction-like fea-
tures, you can construct an entire e-commerce site on MongoDB—not just the prod-
uct content, but the checkout mechanism and the inventory management as well.
To demonstrate, we'll look at two examples of the findAndModify command in
action. First, I'll show how to handle basic state transitions on the shopping cart.
Then we'll look at a slightly more involved example of managing a limited inventory.
6.3.1
Order state transitions
All state transitions have two parts: a query ensuring a valid initial state and an update
that effects the change of state. Let's skip forward a few steps in the order process and
assume that the user is about to click the Pay Now button to authorize the purchase. If
you're going to authorize the user's credit card synchronously on the application side,
then you need to ensure these things:
You authorize for the amount that the user sees on the checkout screen.
1
The cart's contents never change while in the process of authorization.
2
5
The way this command is identified can vary by environment. The shell helper is invoked camel case as
db.orders.findAndModify , whereas Ruby uses underscores: find_and_modify . To confuse the issue
even more, the core server knows the command as findandmodify . You'll use this final form if you ever need
to issue the command manually.
Search WWH ::




Custom Search