Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Schemas and Models

Mongoose Subdocuments, Nested Paths and Arrays

Embed data in Mongoose documents with nested paths, single subdocuments and subdocument arrays, and work with array fields, ids and updates.

MongoDB documents can contain other documents and arrays, and one of the best ways to model data is to keep things that belong together inside one document. Mongoose supports this with three structures that look similar but behave differently: nested paths, single subdocuments and arrays of subdocuments. Knowing which to pick keeps your schemas clear and your queries fast.

Nested paths

The simplest structure is an object whose keys are fields. Mongoose treats address.city as a path, with no separate schema and no _id for the inner object:

JavaScript
const customerSchema = new mongoose.Schema({
  name: String,
  address: {
    street: String,
    city: { type: String, required: true },
    zip: String,
  },
});

const c = new Customer({ name: 'Ada', address: { city: 'London' } });
console.log(c.address.city); // 'London'
c.set('address.zip', 'N1 1AA');

Nested paths are fine for grouping fields. They cannot have their own methods, hooks or validators beyond what the field definitions give.

Single subdocuments

When the inner object needs its own behavior (methods, virtuals, defaults, middleware) define a sub-schema and use it as a field type:

JavaScript
const addressSchema = new mongoose.Schema(
  {
    street: String,
    city: { type: String, required: true },
    country: { type: String, default: 'UK' },
  },
  { _id: false } // no separate id for this embedded object
);

addressSchema.virtual('label').get(function () {
  return `${this.street}, ${this.city}`;
});

const customerSchema = new mongoose.Schema({
  name: String,
  billing: addressSchema,
  shipping: addressSchema,
});

The same sub-schema can be reused for several fields. By default a subdocument gets its own _id; set { _id: false } if you do not need it, which also saves space.

Arrays of subdocuments

Wrap a sub-schema in an array and you get a document array, a list of embedded documents, each with its own _id and behavior:

JavaScript
const commentSchema = new mongoose.Schema({
  author: String,
  text: { type: String, required: true },
  likes: { type: Number, default: 0 },
}, { timestamps: true });

const postSchema = new mongoose.Schema({
  title: String,
  comments: [commentSchema],
  tags: [String],
});

const Post = mongoose.model('Post', postSchema);

const post = new Post({ title: 'Hello' });
post.comments.push({ author: 'Bob', text: 'First!' });
post.comments.push({ author: 'Cleo', text: 'Nice post' });
await post.save();

Working with a document array

Document arrays are enhanced arrays with useful helpers:

JavaScript
const first = post.comments[0];
console.log(first._id);                    // each has its own _id

const byId = post.comments.id(first._id);  // find by _id
byId.likes += 1;

post.comments.pull(first._id);             // remove by id (or: first.deleteOne())
post.comments.addToSet('x');               // for primitive arrays: add if absent

await post.save();                         // saves all changes in one go

Validation runs on every embedded document, so a comment without text makes the whole post fail to save, and the error path looks like comments.0.text.

Primitive arrays

Arrays of strings or numbers (tags: [String]) behave like normal arrays, with one caution: assigning by index does not mark the array as modified. Mongoose detects push, pull, splice and whole-array assignment, but post.tags[0] = 'new' may not be saved. Use post.tags.set(0, 'new') or post.markModified('tags').

The stand-in below imitates the id-based helpers of a document array so you can experiment without Mongoose.

Node.js A document array with ids (stand-in, not Mongoose)

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.

Embed or reference?

Subdocuments live inside the parent, so you read everything in one query. That is excellent for data that is always loaded together and owned by the parent (order lines, comments on a small post, addresses). It is a poor fit when:

  • the array can grow without bound (the 16 MB document size limit eventually bites),
  • the embedded item is read or updated on its own very often,
  • many parents share the same item (duplication, inconsistent copies).

In those cases use a separate collection and a reference (ObjectId with ref), which the population chapter covers.

flowchart LR
  subgraph Embedded
    P1["Post document"] --> C1["comments: [ ... ]"]
  end
  subgraph Referenced
    P2["Post document"] -. "ObjectId" .-> C2["Comment documents<br/>(own collection)"]
  end

Embedded data travels with the parent; referenced data lives in its own collection.

Updating arrays safely

Loading, changing and saving a whole document is easy but can overwrite concurrent changes by another request. For single-field changes, use atomic update operators:

JavaScript
// push a comment without loading the post
await Post.updateOne({ _id: id }, { $push: { comments: { author: 'Dee', text: 'Hi' } } });

// increment a like on one comment using the positional operator
await Post.updateOne(
  { _id: id, 'comments._id': commentId },
  { $inc: { 'comments.$.likes': 1 } }
);

These run entirely inside MongoDB and avoid read-modify-write races. The update lesson later in this chapter lists the array operators.

Defaults and empty arrays

An array field always defaults to [], so post.tags.length is safe to read. If you need the field to stay undefined until set, write tags: { type: [String], default: undefined }.

Common mistakes

  • Forgetting { _id: false } on sub-schemas that do not need an id, bloating documents.
  • Assigning arr[0] = x and expecting it to save.
  • Embedding an unbounded list (every click event of a user) in one document.
  • Saving the parent after modifying a deleted subdocument reference.
  • Trying to save() a subdocument on its own: subdocuments are saved through their parent.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you find a subdocument by id in a Mongoose document array?

    Document arrays provide .id() to look up an embedded document by its _id.
  2. 2. What does { _id: false } on a sub-schema do?

    Without it every subdocument gets its own _id. Disabling it saves space when you do not need one.
  3. 3. Which situation favors a reference instead of embedding?

    Unbounded arrays risk the 16 MB document limit, and a separate collection scales better.
  4. 4. Why might post.tags[0] = 'new' not be saved?

    Use tags.set(0, 'new') or markModified('tags') so Mongoose knows the array changed.

Summary

  • Nested paths group fields; sub-schemas make single subdocuments with their own behavior; [subSchema] makes document arrays.
  • Document arrays offer .id(), .pull(), .push(), and validate every element on save.
  • Use { _id: false } when subdocuments do not need ids and markModified or .set() for index changes.
  • Embed data owned by the parent and read together; reference data that is large, shared or unbounded.
  • Atomic operators such as $push and $inc avoid race conditions.

Next: Creating documents