MongoDB and Mongoose

Intermediate · 34 min

Using MongoDB from Node with the official driver versus Mongoose, defining schemas and validation, adding indexes, and populating references.

Before thisSQL databases with Node and connection pools

Web Dev Simplified · 34 min

MongoDB and Mongoose

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Web Dev SimplifiedReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • MongoDB stores JSON-like documents in collections and does not enforce a schema. The official `mongodb` driver gives you the raw operations, and Mongoose adds schemas, validation, casting, middleware and a model layer on top.
  • A Mongoose schema declares types, `required`, `min`, `minlength`, `unique`, `lowercase` and similar rules. `Model.create()` validates before saving and throws a `ValidationError` that lists each failing field.
  • `unique: true` is an index, not a validator. A duplicate raises a MongoDB error with code `11000` from the database, and the index has to be built (`Model.init()`) before it protects you.
  • Without an index, a filter on a field scans the whole collection. `explain()` shows `COLLSCAN` for a scan and `IXSCAN` for an index lookup. Index the fields you filter and sort by.
  • MongoDB has no joins. References store another document's `_id`, and `.populate('author')` makes a second query that fills in the referenced documents. Embedding data inside the document avoids that second query when the data is read together.
  • `.lean()` returns plain objects instead of full Mongoose documents. It is faster and lighter for read-only responses, but you lose getters, virtuals and `save()`.
  • Schema rules live in the application. The driver, or any other client, can write documents that break them, so the database is only as consistent as every writer.

Documents instead of rows

A relational database makes you decide the shape of your data up front: tables, columns, types, foreign keys. MongoDB starts from the other end. You store JSON-like documents, group them into collections, and the database does not insist that two documents in the same collection look alike. A user can have an address object in one document and none in the next.

That flexibility is useful when the data is naturally nested and mostly read as a unit, such as a product with its variants. It becomes a liability when you assume a shape that nothing guarantees. When to choose a document store at all is argued in relational vs NoSQL databases in practice. This lesson takes the choice as made and shows how Node code works with it.

The driver, and why most people add Mongoose

The official mongodb driver is a thin, accurate wrapper over the database’s operations. You get a collection and call insertOne, find, updateOne:

const users = db.collection('users');
await users.insertOne({ email: 'raw@x.y', name: 1, age: -5 });

That inserted successfully when I ran it. Nothing checks the types or the negative age, because the driver has no idea what a valid user is. Every piece of code that writes to the collection must agree on the shape by convention.

Mongoose moves that agreement into code. You declare a schema, compile it into a model, and use the model for all reads and writes. It adds validation, type casting, defaults, middleware hooks, virtual fields and populate. The trade is some weight and some magic. Mongoose is a good fit for application code with many writers. For one-off scripts or highly dynamic data, the plain driver is often enough. Both can be used on the same connection.

I ran everything below against a real mongod (an in-memory instance from mongodb-memory-server) with Mongoose 9. The video is from 2021, on Mongoose 6, so some details differ, which the video section below lists.

Schemas and validation

import mongoose from 'mongoose';

const userSchema = new mongoose.Schema({
  email: { type: String, required: true, unique: true, lowercase: true, trim: true },
  name:  { type: String, required: true, minlength: 2 },
  age:   { type: Number, min: 0 },
}, { timestamps: true });

const User = mongoose.model('User', userSchema);

await mongoose.connect(process.env.MONGODB_URI);
const ada = await User.create({ email: ' Ada@Example.com ', name: 'Ada', age: 36 });
console.log(ada.email); // 'ada@example.com', trimmed and lowercased on the way in

Setters such as lowercase and trim transform the value before saving. timestamps: true adds createdAt and updatedAt. If validation fails, the save throws before touching the database:

try { await User.create({ email: 'x@y.z', name: 'A' }); }
catch (err) { console.log(err.name, Object.keys(err.errors), err.errors.name.kind); }
// ValidationError [ 'name' ] minlength

The error object lists every failing field, which maps well onto API error responses. Remember that this is validation of what your code sends. User input still needs checking at the edge, as covered in input validation and injection attacks. One MongoDB-specific danger is operator injection: if you pass a parsed request body straight into a filter, an attacker can send {"password": {"$ne": null}}. Cast or validate fields to strings first.

Indexes: unique is not validation

unique: true creates a unique index. That is a database feature, not a Mongoose check, and two consequences follow. A duplicate email fails with a MongoDB error carrying code 11000, not a ValidationError, so handle it separately. And the index only protects you once it exists. Mongoose builds indexes in the background after connecting, so in tests and startup scripts, await User.init() first.

Indexes also decide whether queries are fast. With no index, a filter reads every document. explain() shows which strategy MongoDB chose:

const postSchema = new mongoose.Schema({
  title:  { type: String, required: true },
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, index: true },
  tags:   [String],
});
postSchema.index({ author: 1, title: 1 }); // compound index

const plan = await Post.find({ author: ada._id }).explain('queryPlanner');
console.log(plan.queryPlanner.winningPlan.inputStage.stage); // 'IXSCAN'

On my run, filtering by author showed an IXSCAN, and filtering by the unindexed tags field showed a COLLSCAN. That is the difference between reading a few documents and reading all of them. The same reasoning as relational indexes applies: index what you filter and sort by, and remember that each index slows writes a little.

References and populate

MongoDB has no joins in the relational sense. To link a post to a user, you store the user’s _id in the post, which is what ref: 'User' declares. Reading both means two queries, and populate does the second one for you:

const posts = await Post.find().sort({ title: 1 }).populate('author', 'name email').lean();
// [ { title: 'First', author: { _id, name: 'Ada', email: ... } }, ... ]

Mongoose collects the author ids from the result and fetches them in one extra query. That is better than one query per post, but it is still a second round trip, and populating a large result can get expensive. This is the same shape as the N+1 problem, so populate only what you will show.

The alternative is embedding: put the related data inside the document. A comment list that is always read with its post, or an address that belongs to one user, is a good candidate. Embed when data is read together, bounded in size and owned by one parent. Reference when it is shared, large, unbounded or changes independently. Getting this choice right matters more than any API detail.

Lean documents

By default, Mongoose returns full document objects, with getters, virtuals, change tracking and save(). For a read-only API response, that is overhead. .lean() returns plain JavaScript objects instead. In my run the normal query returned instances of model and the lean one plain Object. Use lean for reads you only serialize, and the full document when you intend to modify and save it.

What the video covers

Web Dev Simplified’s thirty-minute crash course is chaptered: Mongoose basics, schema types, schema validation, query basics, schema methods and virtuals, and schema middleware. It covers the model and validation parts of this lesson well. It has no chapter on indexes or populate, so those sections come from the prose above. It was recorded in 2021 against Mongoose 6. Current Mongoose is 9, where callback-style APIs have been removed, so use await as in the video’s own code, and check the migration guides if you copy an older snippet. The video’s transcript was not available, so this description comes from its chapters and description.

Where this fits

This closes the data group, from configuration through SQL, ORMs and SQLite to documents. Whatever store you choose, you will want tests that exercise it, which starts with the built-in test runner.

Check yourself

  1. 01What does Mongoose add that the plain MongoDB driver does not?

    A schema layer in the application: typed fields with casting, validation rules, defaults, virtuals, middleware hooks and model methods. The driver gives you collections and raw operations. In a test I inserted a document with a negative age through the driver and it was accepted, while the same data through the model would have failed validation.

  2. 02You mark `email` as `unique: true`, but duplicates still get in during a test run. What might be wrong?

    Uniqueness is enforced by a database index, and Mongoose builds indexes asynchronously after connecting. If writes happen before the index exists, duplicates can slip in. Await `Model.init()` in tests and startup, or manage indexes through migrations in production. Also note that `unique` is not a validator, so the error you get on a duplicate is a MongoDB `11000` error, not a `ValidationError`.

  3. 03A query for posts by author is slow on a large collection. How do you check why?

    Run `.explain()` on the query and read the winning plan. A `COLLSCAN` stage means every document was examined. Add an index on the filtered field, for example `author: { index: true }` or `schema.index({ author: 1, title: 1 })`, and the plan should show `IXSCAN`.

  4. 04When should you embed related data in a document instead of referencing it and using populate?

    Embed when the data is read together, is bounded in size, and belongs to one parent, such as an address or a few order line items. Reference and populate when the related documents are shared, large, grow without limit or change independently. Populate costs an extra query, and MongoDB has no real join.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark