An in-memory array will lose all its data every time the server restarts. To persist our data permanently, we must connect our API server to a database.
In this lesson, we will use MongoDB, a popular NoSQL document-based database, alongside Mongoose, an ODM (Object Data Modeling) library for Node.js.
Advertisement
Nextsem Academy
Lesson: p5-3-mongodb
Slide 1 / 6
P5.3: MongoDB & Mongoose
An in-memory array will lose all its data every time the server restarts. To persist our data permanently, we must connect our API server to a database.
In this lesson, we will use MongoDB, a popular NoSQL document-based database, alongside Mongoose, an ODM (Object Data Modeling) library for Node.js.
Slide 2 / 6
1. Relational (SQL) vs Document (NoSQL) Databases
SQL Databases (MySQL, PostgreSQL): Store data in strict rows and columns (tables).
NoSQL Databases (MongoDB): Store data in flexible, JSON-like documents.
Example
// Example of a MongoDB document
{
"_id": "60c72b2f9b1d8b2a3c8e4d5f",
"title": "Learn Express",
"isCompleted": false,
"createdAt": "2026-07-07T12:00:00Z"
}
Interactive Code
Slide 3 / 6
2. Setting Up Mongoose
Mongoose provides a schema-based solution to model your application data. It includes built-in type casting, validation, and query building.
Step 1: Install Mongoose
>_Command Prompt
─☐✕
npm install mongoose
Interactive Console
Step 2: Connect to MongoDB Atlas
Example
const mongoose = require('mongoose');
// Connect to local or cloud MongoDB instance
mongoose.connect('mongodb://localhost:27017/nextsem_db')
.then(() => console.log('Successfully connected to MongoDB!'))
.catch(err => console.error('Database connection error:', err));
Interactive Code
Slide 4 / 6
3. Defining Schemas and Models
A Schema defines the structure of the document (its fields, types, and validations). A Model is a class constructed from the Schema that handles database queries.