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
| Type | JavaScript Equivalent | Example |
|---|---|---|
String | string | "Ryu" |
Number | number | 5 |
Boolean | boolean | true |
Date | Date object | new Date() |
Array | array | ["stealth", "combat"] |
ObjectId | MongoDB ID | Reference to another document |
Validation Options
| Option | Applies To | Purpose |
|---|---|---|
required | All types | Field must have a value |
min / max | Number, Date | Value range limits |
minlength / maxlength | String | Character count limits |
enum | String | Restrict to specific values |
match | String | Must match a regex pattern |
default | All types | Default value if not provided |
trim | String | Remove 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, andmatch timestamps: trueautomatically tracks creation and modification dates