Chapter 8 of 10
Most Express APIs connect to a database. We'll cover MongoDB with Mongoose (the most common pairing with Node.js) and briefly show the pattern for SQL databases.
npm install mongoose// db.js
const mongoose = require("mongoose");
async function connectDB() {
await mongoose.connect(process.env.MONGODB_URI);
console.log("Connected to MongoDB");
}
module.exports = connectDB;
// models/Course.js
const mongoose = require("mongoose");
const courseSchema = new mongoose.Schema({
title: { type: String, required: true, trim: true },
slug: { type: String, required: true, unique: true },
description: { type: String },
level: { type: String, enum: ["beginner", "intermediate", "advanced"] },
chapters: { type: Number, default: 0 },
isLive: { type: Boolean, default: false },
createdAt: { type: Date, default: Date.now },
});
module.exports = mongoose.model("Course", courseSchema);const Course = require("./models/Course");
// Create
const course = await Course.create({
title: "JavaScript Basics",
slug: "javascript-basics",
level: "beginner",
});
// Read
const all = await Course.find({ isLive: true });
const one = await Course.findById(id);
const bySlug = await Course.findOne({ slug: "nextjs" });
// Read with filters, sort, limit
const courses = await Course
.find({ level: "beginner" })
.sort({ createdAt: -1 })
.limit(10)
.select("title slug level"); // only return these fields
// Update
await Course.findByIdAndUpdate(id, { chapters: 14 }, { new: true });
// Delete
await Course.findByIdAndDelete(id);