agyanadda@gmail.com

Node.js with MongoDB and Mongoose

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 20 of 30

MongoDB is a NoSQL database that stores documents (JSON-like objects) in collections. It is very popular with Node.js (the "MERN" stack).

Get a database

Install MongoDB locally, or create a free cluster on MongoDB Atlas and copy its connection string into .env as MONGODB_URI.

Mongoose

Mongoose adds schemas, validation and helpful methods: npm install mongoose.

  1. Connect: await mongoose.connect(process.env.MONGODB_URI)
  2. Define a schema — fields, types, rules
  3. Create a model: mongoose.model('Book', bookSchema) → collection books

CRUD

  • Create: Book.create({ ... })
  • Read: Book.find({ price: { $lt: 500 } }), Book.findById(id), .sort(), .limit()
  • Update: Book.findByIdAndUpdate(id, data, { new: true, runValidators: true })
  • Delete: Book.findByIdAndDelete(id)

Every document gets a unique _id. Add { timestamps: true } to a schema for createdAt and updatedAt.

Relations use ref and .populate().

Example

Example — Book model and routes JavaScript
// models/Book.js
import mongoose from 'mongoose';

const bookSchema = new mongoose.Schema({
  title:  { type: String, required: true, trim: true },
  author: { type: String, required: true },
  price:  { type: Number, min: 0, default: 0 },
  tags:   [String],
}, { timestamps: true });

export default mongoose.model('Book', bookSchema);

// app.js
import express from 'express';
import mongoose from 'mongoose';
import Book from './models/Book.js';

await mongoose.connect(process.env.MONGODB_URI);
const app = express();
app.use(express.json());

app.get('/api/books', async (req, res) => {
  const books = await Book.find().sort({ createdAt: -1 }).limit(20);
  res.json(books);
});

app.post('/api/books', async (req, res) => {
  try {
    res.status(201).json(await Book.create(req.body));
  } catch (err) {
    res.status(400).json({ error: err.message });   // validation errors
  }
});

app.listen(3000);

POST /api/books with {"title":"Wings of Fire","author":"A.P.J. Abdul Kalam","price":299} saves a document with an _id and timestamps. Missing the author returns 400 with Mongoose's validation message.

Test Yourself With Exercises

Exercise 1 Multiple Choice

In MongoDB, a single record is called a…

Exercise 2 True / False

Mongoose's timestamps option adds createdAt and updatedAt fields.

Exercise 3 Fill in the Blank

Load related documents with the ___() method.

Frequently Asked Questions

Use MySQL or PostgreSQL when data is strongly related and needs transactions (orders, payments, accounts). MongoDB suits flexible, document-shaped data (content, logs, catalogues). Both work well with Node.js.