Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Population and Relations

Embedding or Referencing Data

Decide when to embed subdocuments and when to reference other collections in Mongoose - read patterns, document size, atomicity, duplication, and a runnable comparison of both models.

The most important modeling question in a document database is not "which fields?" but "what lives together?" A relational database pushes you to normalize: each fact once, joined at read time. MongoDB lets you store related data inside the same document, so a single read returns everything. Mongoose supports both styles: embedded subdocuments and references with populate.

Neither is "right". The choice depends on how the data is read, how it changes, and how big it can grow. This lesson gives you a short list of questions and a runnable comparison.

The two shapes

Embedding, where the comments sit inside the post:

JavaScript
const postSchema = new Schema({
  title: String,
  comments: [new Schema({ text: String, by: String, at: Date })],
});

Referencing, where comments are their own collection:

JavaScript
const commentSchema = new Schema({
  post: { type: Schema.Types.ObjectId, ref: 'Post', index: true },
  text: String, by: String, at: Date,
});

With embedding, Post.findById(id) returns the post and all comments in one query, and an update to the post and a comment can be atomic because it is one document. With referencing, the comment list is a second query (or virtual populate), but comments can be queried, paginated and indexed independently.

Six questions to decide

  1. Are the children read together with the parent almost always? If yes, lean toward embedding (an address inside a user, line items inside an order).
  2. Is the number of children bounded? A user has a few addresses; a post may have a million comments. Unbounded arrays push a document toward the 16 MB limit and slow every read and write of the parent. Reference those.
  3. Are children accessed on their own? If you list "latest comments across all posts" or "all orders by product", the children need their own collection.
  4. Is the child shared by many parents? A tag, a product, an author used in thousands of posts. Embedding means duplicating and updating copies. Reference it.
  5. Must the child change independently and often? Frequent updates to a deep array element are awkward (positional operators, arrayFilters) and rewrite more data.
  6. Do you need atomic updates across parent and child? Single-document operations are atomic in MongoDB without transactions. Embedding gives you that for free (see Transactions and sessions for the alternative).
flowchart TD
  Q1{"Read together<br/>almost always?"} -- yes --> Q2{"Bounded size?"}
  Q1 -- no --> R["Reference"]
  Q2 -- yes --> Q3{"Shared by many<br/>parents?"}
  Q2 -- no --> R
  Q3 -- no --> E["Embed"]
  Q3 -- yes --> R

A rough decision tree; the right answer can also be a hybrid.

Seeing the difference

The stand-in below stores an order both ways and counts how many "reads" each needs to render an order page, and how a price change on a product affects them.

Node.js Embedded or referenced order (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 the last line. For an order, the embedded copy is usually correct: the customer paid the price at purchase time, and the catalog price changing later must not rewrite history. That is a case where duplication is a feature. The total of the referenced order silently changed to 14 because it read today's price.

Hybrid: embed a summary, reference the rest

Many schemas do both. A post stores the author's _id and a copy of the display name and avatar (so the post list renders with no second query), while the full user document stays in users. The copy is called an extended reference.

JavaScript
const postSchema = new Schema({
  title: String,
  author: {
    _id: { type: Schema.Types.ObjectId, ref: 'User' },
    name: String,   // copied on write; cheap to read
  },
});

The cost is that a rename must update many posts. That is acceptable when names change rarely and reads are frequent.

Node.js Extended reference and its update cost (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.

In Mongoose that cleanup is one updateMany run from a post('save') hook or a job.

Subdocuments and arrays in Mongoose

Embedded subdocuments get their own _id and validation. Useful methods on a document array: push, id(someId) to find by _id, and .pull(id) or .remove-style updates through $pull. Save the parent to persist changes. For large arrays, update with an atomic operator instead of load-modify-save, which can overwrite concurrent edits:

JavaScript
await Post.updateOne({ _id: postId }, { $push: { comments: { text: 'Hi', by: 'Ada' } } });

Rules of thumb

  • Embed: one-to-few, always read together, owned by exactly one parent, snapshot data (order lines, addresses).
  • Reference: one-to-many (large), many-to-many, shared entities, children queried alone.
  • For many-to-many (students and courses), store ids on the side that is smaller and bounded, or use a join collection with two references and a compound unique index.
  • Model for your queries, not your diagram. If a screen needs two collections' data at once, consider copying the few fields it needs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An order stores line items with the price paid. Which approach protects history from later catalog price changes?

    A snapshot is intentional duplication: the line keeps what the customer actually paid.
  2. 2. A post can have millions of comments. What is the best shape?

    Unbounded arrays threaten the 16 MB document limit and slow every read of the parent.
  3. 3. What is an extended reference?

    You keep the _id for the full document and copy display fields to avoid a join on common reads.
  4. 4. Which is an advantage of embedding?

    Everything in one document means one read and atomic updates without a transaction.

Summary

  • Embed data that is bounded, owned and read together; reference data that is large, shared or queried alone.
  • Duplication is fine when it is a snapshot or a rarely changing display field.
  • Embedding gives single-read speed and atomic updates; referencing gives independence and no duplication.
  • Hybrids (extended references) are common.
  • Design from your queries, and revisit as access patterns change.

Next: Aggregation pipeline basics