CPCODELAB
MongoDB

Mongoose: Schemas and Models

13 min read

Mongoose: ODM for Node.js

Mongoose is the most popular Object Document Mapper (ODM) for MongoDB in Node.js. It adds schemas, models, validation, middleware (hooks), and type casting on top of the native driver.

Defining a Schema and Model

js
import mongoose, { Schema } from "mongoose";

const studentSchema = new Schema({
  name:     { type: String, required: true, trim: true },
  email:    { type: String, required: true, unique: true, lowercase: true },
  age:      { type: Number, min: 16, max: 60 },
  course:   { type: String, enum: ["Full Stack", "Data Science", "DevOps"] },
  enrolled: { type: Boolean, default: false },
  tags:     [String]
}, { timestamps: true });

const Student = mongoose.model("Student", studentSchema);
export default Student;

CRUD with Mongoose

js
// Create
const student = await Student.create({ name: "Nisha", email: "nisha@example.com", course: "Full Stack" });

// Read
const found = await Student.findOne({ email: "nisha@example.com" });

// Update
await Student.findByIdAndUpdate(found._id, { $set: { enrolled: true } }, { new: true });

// Delete
await Student.findByIdAndDelete(found._id);

Pass { new: true } to findByIdAndUpdate to get the updated document back instead of the original.

Ready to test yourself?
Practice MongoDB— quiz & coding exercises