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.
- Connect:
await mongoose.connect(process.env.MONGODB_URI) - Define a schema — fields, types, rules
- Create a model:
mongoose.model('Book', bookSchema)→ collectionbooks
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
// 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.