Skip to content

Mongoose

Schema, Model and Documents

The three objects you will touch in every Mongoose file.

IntermediateAbout 5 minutes

Three names. Schema — the shape and types. Model — the class bound to a collection (Userusers by default). Document — one hydrated record, with .save(). Mixing them up is how people call new Schema().find().

import mongoose, { Schema } from "mongoose";

const userSchema = new Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    city: String,
    age: Number,
    skills: [String],
  },
  { timestamps: true }
);

export const User = mongoose.model("User", userSchema);
Schema → model. Collection name is pluralised `users`.
const orderSchema = new Schema({
  userId: { type: Schema.Types.ObjectId, ref: "User", required: true },
  amount: Number,
  status: { type: String, enum: ["pending", "shipped", "delivered", "cancelled"] },
  items: [{ name: String, quantity: Number, unitPrice: Number }],
});

export const Order = mongoose.model("Order", orderSchema);
Order references a user — still just an ObjectId in MongoDB

unique: true on the schema creates an index; it is not the same as required validation. strict (default) strips fields not in the schema on save — a driver insert can still store them. timestamps adds createdAt / updatedAt. Override the collection with { collection: "app_users" } when you do not want users.

Interview question

What is the difference between a Mongoose schema, model and document?

Think about it first.