Simplifying MongoDB with Mongoose

Learn what an ODM does and use Mongoose schemas and models for CRUD operations and data validation.

🎯 Introduction

Previously, we used the official driver to read and write MongoDB data from Node.js. You may have noticed that MongoDB does not enforce a document structure by default: documents in the same collection can have different fields. This flexibility is helpful in small projects, but can become difficult to manage as a project grows.

In this article, you will learn what an ODM is, define schemas and models with Mongoose, simplify CRUD operations, and apply automatic validation to keep invalid data out of the database.


🧱 Why Use Mongoose?

Without configured validation, MongoDB accepts whatever structure you write. In the user collection, you might write username once and accidentally write usernmae next time; both are accepted. An age can likewise be a number in one document and a string in another.

This is manageable while learning, but inconsistent documents can make query results unpredictable and debugging difficult in larger projects.

Mongoose addresses this problem. It is an ODM (Object Document Mapping) tool that adds structural constraints and validation. You define field names, types, required fields, and allowed ranges in code, and reject data that fails these rules.

Think of the official driver as a blank notebook where you can write freely, and Mongoose as a structured registration form with rules for each entry. Incorrect entries are rejected immediately.


🛠 Installing and Connecting

This article was written and tested with Node.js v22 LTS and Mongoose 9.x. We will reuse the mongo-demo Docker container: mongo:8, port 27017, username root, and password 123456.

If the container is stopped, start it with docker start mongo-demo.

Create and initialize a project directory, then install mongoose:

mkdir node-mongoose && cd node-mongoose
npm init -y
npm install mongoose

Create db.js to handle the database connection:

db.js
const mongoose = require('mongoose');

async function connect() {
    await mongoose.connect(
        'mongodb://root:123456@localhost:27017/blog_demo?authSource=admin'
    );
    console.log('Connected to MongoDB');
}

module.exports = connect;

Three parts of the connection string deserve attention:

  • localhost:27017 is the host and port exposed by the Docker container.
  • /blog_demo specifies the database name directly in the connection string. It becomes the default database after connecting and is created when needed.
  • ?authSource=admin checks credentials against admin. The root account was created there, so omitting this parameter causes authentication to fail. This is a common issue when connecting to a password-protected MongoDB instance.

✨ Defining a Schema and Model

Mongoose has two core concepts: schemas and models:

  • Schema: Describes the structure of documents in a collection, like the fields on a registration form.
  • Model: An interface compiled from a schema, through which you perform CRUD operations.

Define a schema for user documents:

user.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    username: { type: String, required: true },
    age: { type: Number, min: 0, max: 150 },
    city: { type: String, default: 'Unknown' },
});

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

module.exports = User;

Let's examine each field:

  • username: A string. required: true makes it mandatory; omitting it causes an error.
  • age: A number. min and max restrict it to 0 through 150.
  • city: A string. default: 'Unknown' supplies Unknown when the field is omitted.

mongoose.model('User', userSchema) creates the User model. The first argument, 'User', is the model name. By convention, Mongoose converts it to a lowercase plural collection name, users, without you specifying that name manually.

Earlier articles used user, while Mongoose defaults to users. To keep using user, provide the third argument explicitly: mongoose.model('User', userSchema, 'user').

💡 CRUD Operations with a Model

With a model, CRUD operations are straightforward and the method names describe their purpose:

crud.js
const connect = require('./db');
const User = require('./user');

async function main() {
    await connect();

    // Create
    const user = await User.create({ username: 'Xiao Ming', age: 20, city: 'Beijing' });
    console.log('User created:', user);

    // Find all users
    const users = await User.find();
    console.log('Users:', users);

    // Find a user by ID
    const found = await User.findById(user._id);
    console.log('User by ID:', found);

    // Update
    await User.updateOne({ _id: user._id }, { age: 26 });

    // Delete
    await User.deleteOne({ _id: user._id });

    process.exit(0);
}

main();

Compared with the official driver, create corresponds to insertOne, find corresponds to find, and updateOne and deleteOne keep the same names. However, create returns the complete created document without another query, and query results are document objects shaped by the schema.

Now try validation by creating a document without username:

await User.create({ age: 20, city: 'Beijing' });

This throws a ValidationError explaining that username is required. Setting age to 200 also fails because it exceeds max: 150. Invalid data is rejected before it reaches the database: that is the value of a schema.


⚖️ Choosing Between Mongoose and the Official Driver

Neither tool is best for every situation. Choose based on the task:

  • Official driver: Closer to native MongoDB syntax, with a smaller package. It is a lightweight choice for one-off scripts, migration tools, or fine control over queries.
  • Mongoose: Includes structure definitions and validation, plus advanced features such as middleware and population. For teams building applications with consistent fields, it reduces validation code and makes structure clearer.

A useful starting point is the driver for short scripts, Mongoose for business applications. Mongoose is a common choice for application development.


❓ Questions and Answers

Q1: How does ODM relate to ORM?

Both map code objects to database data. An ORM works with relational tables and rows; an ODM works with collections and documents in databases such as MongoDB.

Q2: Can I write fields that are not in the schema?

Not by default. Mongoose discards undeclared fields when writing, helping keep the document structure consistent.

Q3: Will Mongoose fail if my existing collection has no constraints beyond _id?

No. Schema validation applies to writes through Mongoose and does not retroactively validate existing data. You can still query existing documents.

Q4: Can I omit authSource=admin?

Not in this course's Docker environment, because the root account belongs to admin. For an account created in an application database, use that database as the authentication source.

Q5: Does User.updateOne trigger schema validation?

Update validators are disabled by default. Pass { runValidators: true } to enable them. They do not perform full document validation, including checking every required field. For now, remember that this option exists.


🧪 Exercises

Exercise 1: Add a required string email field to userSchema, then create a user document with an email address.

user.js
const userSchema = new mongoose.Schema({
    username: { type: String, required: true },
    age: { type: Number, min: 0, max: 150 },
    city: { type: String, default: 'Unknown' },
    // Write your code here
});

Exercise 2: Write findUsersByCity, accepting a city name and returning all matching users with User.find().

crud.js
async function findUsersByCity(city) {
    // Write your code here
}

🎉 You can now use Mongoose to work with MongoDB! Next, we will explore indexes and how they speed up queries as your data grows.