Chapters of From Frontend to Full-Stack Backend

Week 2 - Database DepthChapter 11 of 282 min read

MongoDB schema design - embed or reference

Document model, the embed vs reference decision, keeping data that is read together in one place

The first mistake a SQL-trained mind makes in MongoDB is splitting collections like tables - users separate, orders separate, then joining them together every time like a JOIN. MongoDB's philosophy is the opposite: keep together the data that is read together. Because in MongoDB JOINs are expensive, but reading a single document is very cheap.

Embed - keeping it inside

Keep an order's items inside the order as an array. When you read the order, the items come along, no separate query needed. Embed works well when: the inner data is never needed alone outside, it stays limited in number, and it changes together with the main document. Addresses, order items, a blog post's tags - these are good embed candidates.

// embed - items inside the order itself
{
  _id: "order_101",
  userId: "user_7",
  status: "delivered",
  items: [
    { productId: "p1", name: "Chicken Biryani", qty: 2, price: 220 },
    { productId: "p2", name: "Borhani", qty: 2, price: 60 }
  ],
  total: 560
}

Reference - keeping only the id

But you cannot embed a product's full information inside an order - the product's price changes, its description changes, and if it is spread across a thousand orders, updating it becomes a nightmare. Data that is independent on its own, used from many places, or can grow without limit (like a post's comments passing a hundred thousand) - there, keep only the id as a reference. Notice in the example above, a snapshot of the item's price was deliberately kept inside the item - because the price at order time is history; even if the price changes later, the old order will not change.

The easy question for the decision is this: 'Will this data ever be needed separately without the main thing? And can it grow without limit?' If the answer to either is yes, reference; otherwise embed.

The mistake everyone makes

Both extremes are wrong: splitting everything like SQL (then you never got MongoDB's benefit), and stuffing everything into one document (the document becomes huge, hits MongoDB's 16MB limit, and the same data duplicated in many places causes update chaos).

Today's practice

Thinking of Khabar Dhandha, sketch the MongoDB schema for menu and orders on paper. Beside every decision write one line of reason - which is embed, which is reference, and why. Then bring that schema into code with Mongoose.

How to say it in an interview

In MongoDB I design schemas by looking at the read pattern - data that is read together, I embed; data that changes independently or can grow without limit, I keep as a reference. SQL's normalization does not carry over exactly here, because here JOINs are expensive and reading a document is cheap.

All chapters of From Frontend to Full-Stack Backend