# Mongoose: Schemas, Models and When Projects Use It

Mongoose is a library built on the MongoDB driver that adds a schema, a model with create, find and findById, and validation before every save, and a project's package.json and model files tell you whether it uses Mongoose or the driver, which is what this course's own code uses.

Journeyman · MongoDB · Node.js · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Define a Mongoose schema and model, and save and find documents with create, find and findById
- Tell whether a project uses Mongoose or the MongoDB driver, and explain what Mongoose's schema and validation add

## Key takeaways

- Mongoose is a library built on the MongoDB driver. You describe a document's fields once, in a schema, and Mongoose checks every save against it.
- mongoose.model("Workout", workoutSchema) makes a model, and the model saves and finds workouts in the workouts collection with create, find and findById.
- Built-in validation, such as required and min, stops a bad save with a ValidationError before anything reaches MongoDB.
- Mongoose adds __v, a version number, to every document it saves, and an _id to every object in an array, such as each set.
- A project uses Mongoose when its package.json lists mongoose and its code has new Schema, mongoose.model and mongoose.connect. This course's code uses the driver.

Clone a Node project from work or from a tutorial, open its `models` folder, and you may find no `db.collection` anywhere. Instead there's `new Schema(…)`, `mongoose.model(…)` and `Workout.findById(…)`. That's **Mongoose**, a library that many Node projects use with MongoDB, so you're likely to meet it. This lesson teaches you to read it, write a little of it, and tell which kind of project you're in.

## Same database, another library

The driver you've used saves whatever object you hand it. Misspell `member` as `memebr` and MongoDB stores the typo without a word. Mongoose sits on top of the driver and adds a description of what a document should look like, checked before every save. It's an **ODM**, an object document mapper: it maps your JavaScript objects to MongoDB documents and back. In a project folder, install it:

```bash
npm install mongoose
```

## A schema and a model

A **schema** is the shape of one kind of document: each field, its type, and its rules. Think of the printed workout card at the gym's front desk, with a line for the member's name, a line for the date, and a row for each set. Make `workoutModel.js`:

```javascript
import mongoose from "mongoose";

const workoutSchema = new mongoose.Schema({
  member: { type: String, required: true },
  date: { type: String, required: true },
  sets: [{ exercise: String, reps: { type: Number, min: 1 }, weight: Number }],
});

export const Workout = mongoose.model("Workout", workoutSchema);
```

`mongoose.model("Workout", workoutSchema)` makes a **model**: the object you save and find workouts with. Mongoose names the collection for you from the model's name, lowercased and made plural: `workouts`, the same collection the driver's code uses.

## Saving and finding

`mongoose.connect` connects once for the whole program, and `dbName` picks the database. Then the model does the work. Make `save-and-find.js`:

```javascript
import mongoose from "mongoose";
import { Workout } from "./workoutModel.js";

await mongoose.connect(process.env.MONGODB_URI, { dbName: "rep_counter" });

const saved = await Workout.create({
  member: "Keiko",
  date: "2026-11-17",
  sets: [{ exercise: "row", reps: 12, weight: 70 }],
});
console.log(saved);

const found = await Workout.findById(saved._id);
console.log(found.member, found.date);

const keikos = await Workout.find({ member: "Keiko" });
console.log(keikos.length);

await mongoose.disconnect();
```

```bash
node --env-file=.env save-and-find.js
```

```text
{
  member: 'Keiko',
  date: '2026-11-17',
  sets: [
    {
      exercise: 'row',
      reps: 12,
      weight: 70,
      _id: new ObjectId('6afc96174f492eb60b0316a7')
    }
  ],
  _id: new ObjectId('6afc96174f492eb60b0316a6'),
  __v: 0
}
Keiko 2026-11-17
1
```

`create` does the job of `insertOne`, `find` of `find().toArray()`, and `findById` turns the id into an ObjectId for you. Two fields you didn't ask for: `__v` (read "underscore v"), a version number Mongoose keeps on each document, and an `_id` on the set, because Mongoose gives every object in an array an id of its own.

## Validation before the save

Now hand the model a workout with no member and a set of 0 reps. Make `bad-workout.js`:

```javascript
import mongoose from "mongoose";
import { Workout } from "./workoutModel.js";

await mongoose.connect(process.env.MONGODB_URI, { dbName: "rep_counter" });

try {
  await Workout.create({ date: "2026-11-17", sets: [{ exercise: "row", reps: 0 }] });
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}

await mongoose.disconnect();
```

```text
ValidationError
Workout validation failed: sets.0.reps: Path `reps` (0) is less than minimum allowed value (1)., member: Path `member` is required.
```

Mongoose checked the workout against the schema and refused it with a **ValidationError** naming every problem, and nothing reached MongoDB. `required` and `min` are two of its built-in rules; *Checking Input by Hand* wrote the same kind of checks yourself.

## Driver or Mongoose: how to tell

| Look at | The driver | Mongoose |
|---|---|---|
| `package.json` | `"mongodb"` | `"mongoose"` |
| Connecting | `new MongoClient(uri)` | `mongoose.connect(uri)` |
| Describing documents | nothing: any object is saved | `new mongoose.Schema({ … })` |
| Saving and finding | `db.collection("workouts").insertOne(…)` | `Workout.create(…)`, `Workout.findById(…)` |
| A document comes back as | a plain object | a Mongoose document, with `__v` |

This course's own code uses the driver: it's what Mongoose runs on, it shows you what MongoDB really does, and its plain objects need no translating. A repository keeps either one in one file, so the routes look the same. When you join a Mongoose project, read its schemas first: they're the clearest description of its data you'll find.

## Check yourself

2 questions to try on the lesson page.

## So what

Whichever library a project picked, it's the same MongoDB underneath, and now you can read both: the driver's plain calls and Mongoose's schemas, models and validation.

## Key terms

- [Mongoose](https://www.ask-codey.com/glossary/mongoose)
- [MongoDB Driver](https://www.ask-codey.com/glossary/mongodb-driver)
- [Object Document Mapper (ODM)](https://www.ask-codey.com/glossary/object-document-mapper-odm)
- [Mongoose Schema](https://www.ask-codey.com/glossary/mongoose-schema)
- [Mongoose Model](https://www.ask-codey.com/glossary/mongoose-model)

## Related

- [Keeping Database Code in One Place](https://www.ask-codey.com/lessons/node-mongodb-repository-module)
- [Connecting from Node and Saving Documents](https://www.ask-codey.com/lessons/node-mongodb-connect-and-insert)
- [Checking Input by Hand](https://www.ask-codey.com/lessons/node-validation-by-hand)

Source: https://www.ask-codey.com/lessons/node-mongoose-schemas-and-models
