Express.js Mongoose CRUD

Mongoose is a library that connects Express apps to MongoDB with structure and rules. MongoDB stores flexible documents. Mongoose adds schemas and models on top, so every document follows a known shape. CRUD stands for Create, Read, Update, and Delete, the four actions that almost every app performs on data.

Think of a school register. A schema is the printed form with fixed columns such as name, age, and grade. A model is the clerk who adds, finds, changes, and removes rows in that register. Mongoose supplies both.

CRUD and HTTP Methods

CRUD ActionHTTP MethodMongoose Method
CreatePOSTcreate()
ReadGETfind(), findById()
UpdatePUT or PATCHfindByIdAndUpdate()
DeleteDELETEfindByIdAndDelete()

Data Flow Diagram

Client
  |  POST /students
  v
Express route
  |
  v
Mongoose model (Student)
  |  checks schema rules
  v
MongoDB collection "students"
  |
  v
Saved document returns to the client

Install and Connect

npm install mongoose
const mongoose = require('mongoose');

mongoose.connect(process.env.MONGO_URI)
  .then(() => console.log('Database connected'))
  .catch((err) => console.error(err));

Create a Schema and Model

The schema lists each field with its type and rules. The model wraps the schema and exposes the database methods.

const studentSchema = new mongoose.Schema({
  name:  { type: String, required: true, trim: true },
  age:   { type: Number, min: 3, max: 100 },
  grade: { type: String, default: 'A' }
}, { timestamps: true });

const Student = mongoose.model('Student', studentSchema);
module.exports = Student;

The timestamps option adds createdAt and updatedAt fields automatically. Mongoose turns the model name Student into a collection named students.

Build the Four Routes

Create a Document

app.post('/students', async (req, res) => {
  try {
    const student = await Student.create(req.body);
    res.status(201).json(student);
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});

Read Documents

app.get('/students', async (req, res) => {
  const students = await Student.find();
  res.json(students);
});

app.get('/students/:id', async (req, res) => {
  const student = await Student.findById(req.params.id);
  if (!student) return res.status(404).json({ error: 'Not found' });
  res.json(student);
});

Update a Document

app.put('/students/:id', async (req, res) => {
  const student = await Student.findByIdAndUpdate(
    req.params.id,
    req.body,
    { new: true, runValidators: true }
  );
  if (!student) return res.status(404).json({ error: 'Not found' });
  res.json(student);
});

The new option returns the updated document instead of the old one. The runValidators option applies the schema rules during the update.

Delete a Document

app.delete('/students/:id', async (req, res) => {
  const student = await Student.findByIdAndDelete(req.params.id);
  if (!student) return res.status(404).json({ error: 'Not found' });
  res.json({ message: 'Student removed' });
});

Filter, Sort, and Limit

The find method accepts a filter object. Chain sort, limit, and select to shape the result.

const topStudents = await Student
  .find({ grade: 'A', age: { $gte: 10 } })
  .sort({ name: 1 })
  .limit(5)
  .select('name grade');

Tips for Reliable CRUD

  • Wrap every database call in try and catch, or pass errors to the error handler.
  • Return status 404 when a record does not exist.
  • Return status 201 after a successful create.
  • Validate request data before calling the model.
  • Keep the model file separate from the route file.

These four routes form the base of almost every REST API. Swap the Student model for Product, Order, or Post, and the same pattern applies.

Real-World Scenario

A library app tracks books with a Book model. Staff add new arrivals with a POST route, search the catalog with a GET route, fix typos with a PUT route, and remove damaged copies with a DELETE route. Members never touch the database directly. Every action passes through the model, which enforces the schema rules and keeps each record complete and tidy.