Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: An Order System with Stock

Build an order system with Mongoose - products with stock, orders with price snapshots, atomic stock reservation, idempotent checkout, cancellation and a revenue report - with runnable logic.

Orders are where data modeling mistakes cost real money: selling stock you do not have, charging the wrong price, double-processing a retried request. This project builds the core of an order system and applies the chapter's ideas: snapshots, atomic conditional updates, transactions, idempotency keys, indexes and an aggregation report.

As elsewhere in this chapter, the Mongoose code is read-only and a runnable in-memory version reproduces the behavior of each operation.

Requirements

  • Products have a SKU, name, price (in cents, as integers) and stock.
  • A customer places an order with several lines. Each line keeps a snapshot of name and price at purchase time.
  • Stock must never go negative, even with many simultaneous orders.
  • Retrying the same checkout request must not create a second order.
  • An order can be cancelled once, which returns stock.
  • A report shows revenue and units sold per product for paid orders.

Data model

JavaScript
const productSchema = new Schema({
  sku: { type: String, required: true, unique: true },
  name: { type: String, required: true },
  priceCents: { type: Number, required: true, min: 0, validate: Number.isInteger },
  stock: { type: Number, required: true, min: 0, default: 0 },
});

const lineSchema = new Schema({
  product: { type: Schema.Types.ObjectId, ref: 'Product', required: true },
  sku: String,
  name: String,              // snapshot
  priceCents: Number,        // snapshot
  qty: { type: Number, required: true, min: 1 },
}, { _id: false });

const orderSchema = new Schema({
  customer: { type: Schema.Types.ObjectId, ref: 'User', required: true, index: true },
  idempotencyKey: { type: String, required: true, unique: true },
  lines: { type: [lineSchema], validate: (v) => v.length > 0 },
  totalCents: { type: Number, required: true },
  status: { type: String, enum: ['paid', 'cancelled'], default: 'paid' },
}, { timestamps: true });

orderSchema.index({ status: 1, createdAt: -1 });

Money is stored as integer cents; floating-point arithmetic cannot represent 0.10 exactly, and summing prices as floats produces off-by-a-cent errors. Lines are embedded (bounded, owned by the order, read with it) while the product link is kept for reporting. The unique idempotencyKey is the guard for retries, as described in Transactions and sessions.

The checkout operation

Reserving stock uses a conditional atomic update per line: it decrements stock only if enough remains, so two simultaneous orders for the last unit cannot both succeed.

JavaScript
export async function placeOrder(customerId, key, items) {
  const existing = await Order.findOne({ idempotencyKey: key });
  if (existing) return existing;                 // a retry: same answer

  const session = await mongoose.startSession();
  try {
    let order;
    await session.withTransaction(async () => {
      const lines = [];
      for (const { sku, qty } of items) {
        const product = await Product.findOneAndUpdate(
          { sku, stock: { $gte: qty } },
          { $inc: { stock: -qty } },
          { new: true, session },
        );
        if (!product) throw new Error(`Not enough stock for ${sku}`);   // aborts everything
        lines.push({ product: product._id, sku, name: product.name, priceCents: product.priceCents, qty });
      }
      const totalCents = lines.reduce((s, l) => s + l.priceCents * l.qty, 0);
      [order] = await Order.create([{ customer: customerId, idempotencyKey: key, lines, totalCents }], { session });
    });
    return order;
  } catch (err) {
    if (err.code === 11000 && err.keyPattern?.idempotencyKey) {
      return Order.findOne({ idempotencyKey: key });  // a concurrent duplicate won the race
    }
    throw err;
  } finally {
    await session.endSession();
  }
}

Each piece does a job: the filter stock: { $gte: qty } is the guard, the transaction rolls back stock already taken for earlier lines if a later line fails, and the unique key turns a concurrent duplicate into a harmless read.

A runnable version

This in-memory version has the same logic: conditional stock reservation per line with rollback, snapshots, idempotent retry, cancellation and the report. The rollback is manual here (the real transaction does it for you).

Node.js Orders, stock and rollback (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice four properties together: stock never goes below zero, a failed multi-line order leaves stock unchanged, a retry returns the original order, and history is protected from later price changes.

The report in Mongoose

JavaScript
export const salesReport = (from, to) =>
  Order.aggregate([
    { $match: { status: 'paid', createdAt: { $gte: from, $lt: to } } },   // uses { status, createdAt } index
    { $unwind: '$lines' },
    {
      $group: {
        _id: '$lines.sku',
        units: { $sum: '$lines.qty' },
        revenueCents: { $sum: { $multiply: ['$lines.qty', '$lines.priceCents'] } },
      },
    },
    { $sort: { revenueCents: -1 } },
  ]);

Because lines hold snapshots, the report needs no $lookup and reflects prices actually charged.

Concurrency review

Walk through what could go wrong, as you would in a design review:

  • Two buyers, one unit left: both run the conditional update; MongoDB serializes them on the document and only one matches stock >= qty.
  • Crash after stock is taken but before the order exists: the transaction aborts, stock returns. Without transactions you would need a reserved state and a cleanup job.
  • Client times out and retries: the idempotency key makes the retry harmless.
  • Cancel pressed twice: the conditional updateOne({ _id, status: 'paid' }, { status: 'cancelled' }) changes at most one document; return stock only if modifiedCount === 1.
  • Hot product: every order updates one product document and conflicts; if that becomes a bottleneck, split stock across several counter documents.

Extend it

  1. Add a payment sub-step with statuses pending, paid, failed, and a job that cancels orders pending longer than 15 minutes.
  2. Add a coupon model with a usage limit decremented with the same conditional-update trick.
  3. Add per-customer order history with keyset pagination on (customer, _id) and a matching compound index.
  4. Write the integration tests: run 20 concurrent placeOrder calls for 5 units and assert exactly 5 succeed (use MongoMemoryReplSet, see Testing Mongoose code).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store lines with a copy of the price?

    A snapshot preserves the historical price and name.
  2. 2. What stops two buyers from taking the last unit?

    The filter is checked and the decrement applied atomically on the document, so only one update can match.
  3. 3. Why store money as integer cents?

    Binary floating point cannot exactly represent values like 0.10; integer cents avoid rounding errors.
  4. 4. A checkout request is retried after a timeout. What prevents a duplicate order?

    The unique key makes the second insert fail (or the first lookup succeed), so the original order is returned.

Summary

  • Model orders with snapshots of price and name and integer money.
  • Reserve stock with conditional atomic updates inside a transaction.
  • Make operations idempotent with a unique key.
  • Guard state changes (cancel once) with conditions in the update filter.
  • Reports over snapshots need no join.

Next: Practice: Mongoose exercises