Stop 07 · Mongoose ODMTopics · 3/8

Schemas and Models

Part of the MERN Stack Roadmap

In short

MongoDB will store any shape you give it, which is freedom and danger at once. A Mongoose schema writes down the shape you expect, and the model gives you clean methods like Product.find() and Product.create().

A schema defines the shape of documents (field names, types and defaults) and a model is the class you use to create and query documents in a collection.

The jaadu rolls out a large blueprint on a table while small identical model houses stand in a neat row beside it.

Think of it like this

The architect's plan and the builder

An architect draws one plan for a type of flat: rooms, sizes, where the windows go (schema). The builder uses that plan to build real flats, find them and repair them (model). Each actual flat is a document.

Watch it happen

From schema to documents

productSchema
Product model
products collection
doc: Steel Bottle
doc: Notebook

1/4The schema lists fields, types, defaults and options like timestamps.

The big ideas

What you need to know

Types and defaults

String, Number, Boolean, Date, ObjectId, arrays and nested objects. default fills in a value when none is given.

timestamps: true

Adds createdAt and updatedAt and keeps them updated for you.

strict mode

Fields not in the schema are dropped on save by default, so random keys from req.body don't sneak in.

lean() for reads

find().lean() returns plain objects, which is faster when you only send JSON and don't need document methods.

See it in code

Walk through the code

js
1// src/models/product.model.js2import { Schema, model } from "mongoose";3 4const productSchema = new Schema(5  {6    name: { type: String, required: true, trim: true },7    price: { type: Number, required: true },8    category: { type: String, default: "general", index: true },9    tags: [String],10    inStock: { type: Boolean, default: true },11  },12  { timestamps: true }13);14 15export const Product = model("Product", productSchema);16 17// Using it in a service18const p = await Product.create({ name: "Steel Bottle", price: 450, category: "kitchen" });19const kitchen = await Product.find({ category: "kitchen" }).sort({ price: 1 }).lean();20await Product.findByIdAndUpdate(p._id, { $set: { price: 499 } }, { new: true });

1/4Fields with types, required flags, defaults and an index on category.

One schema file per model. The rest of your app imports Product and never writes raw collection code.

Save yourself the pain

Common mistakes

Oops

Storing prices as strings like "450" because the form sent text.

Do this instead

Declare price as Number. Mongoose casts "450" to 450, and rejects values like "abc".

Oops

Defining the same model twice and getting OverwriteModelError.

Do this instead

Define each model once in its own file and import it everywhere.

Your mission

Model a canteen menu

~25 min

Quick check

Which collection will mongoose.model("Category", schema) use by default?

Go deeper

  1. 1Create Product and User schemas with types, required fields and defaults.
  2. 2Add { timestamps: true } so createdAt and updatedAt are set automatically.
  3. 3Keep one model per file in a models folder.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge