Episode 9 of 17

Models & Schemas

Define data models with Mongoose schemas — set field types, validation rules, and defaults for structured MongoDB documents.

Models & Schemas

Before saving data to MongoDB, you need to define the shape of your data. Mongoose is an ODM (Object Data Modeling) library that provides schemas and models — a structured way to define what your data looks like, validate it, and interact with MongoDB.

Installing Mongoose

npm install mongoose

What Is a Schema?

A schema defines the structure of a document in a MongoDB collection — the fields, their data types, validation rules, and default values.

Creating a Schema

// models/ninja.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ninjaSchema = new Schema({
    name: {
        type: String,
        required: [true, 'Name is required'],
        trim: true,
    },
    rank: {
        type: Number,
        required: [true, 'Rank is required'],
        min: [1, 'Rank must be at least 1'],
        max: [10, 'Rank cannot exceed 10'],
    },
    available: {
        type: Boolean,
        default: false,
    },
}, { timestamps: true });

const Ninja = mongoose.model('Ninja', ninjaSchema);
module.exports = Ninja;

Schema Types

TypeJavaScript EquivalentExample
Stringstring"Ryu"
Numbernumber5
Booleanbooleantrue
DateDate objectnew Date()
Arrayarray["stealth", "combat"]
ObjectIdMongoDB IDReference to another document

Validation Options

OptionApplies ToPurpose
requiredAll typesField must have a value
min / maxNumber, DateValue range limits
minlength / maxlengthStringCharacter count limits
enumStringRestrict to specific values
matchStringMust match a regex pattern
defaultAll typesDefault value if not provided
trimStringRemove leading/trailing whitespace

The timestamps Option

{ timestamps: true }

This automatically adds createdAt and updatedAt fields to every document. Mongoose manages these — createdAt is set when the document is created, and updatedAt is refreshed on every save.

What Is a Model?

const Ninja = mongoose.model('Ninja', ninjaSchema);

A model is a constructor compiled from a schema. It provides methods for creating, reading, updating, and deleting documents in the corresponding MongoDB collection. The first argument ('Ninja') becomes the collection name (lowercased and pluralized: ninjas).

Key Takeaways

  • Mongoose schemas define the structure, types, and validation rules for MongoDB documents
  • Models are constructors that provide CRUD methods for interacting with collections
  • Built-in validators include required, min, max, enum, and match
  • timestamps: true automatically tracks creation and modification dates