Hey there, coder champ! π
Ever wondered how apps like YouTube or Amazon store and fetch data?
That magic happens using databases! ποΈ
Today, Iβll teach you how to connect Node.js with databases β both SQL and NoSQL β in a way even your pet πΆ can understand.
Letβs dive in!
π What Is a Database?
A database is like a smart notebook π for your app. It stores data so you can get it anytime you want.
For example:
- π§ββοΈ A userβs name, email
- π Items in a shopping cart
- π§Ύ Blog posts, comments
π₯ SQL vs NoSQL β Whatβs the Difference?
There are 2 big types of databases:
Feature | SQL (Relational) | NoSQL (Non-relational) |
---|---|---|
Stores Data In | Tables (rows + columns) | Collections (documents) |
Language | SQL | JavaScript-like queries |
Best For | Structured data (Banking, ERP) | Flexible data (Social Apps) |
Examples | MySQL, PostgreSQL | MongoDB, Firebase |
π§ Think of SQL like Excel sheets π
And NoSQL like JSON files π¦
π οΈ Letβs Start with NoSQL: MongoDB + Node.js
MongoDB is one of the most popular NoSQL databases. It stores data as JSON-like documents.
Weβll use a library called Mongoose to connect Node.js with MongoDB.
βοΈ Step-by-Step: Connect MongoDB with Node.js
π¦ 1. Setup Project
bashCopyEditmkdir mongo-demo
cd mongo-demo
npm init -y
npm install express mongoose
π§ͺ 2. Create Server
jsCopyEdit// index.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
mongoose.connect('mongodb://localhost:27017/mydb')
.then(() => console.log('β
Connected to MongoDB'))
.catch((err) => console.error('β MongoDB connection failed:', err));
app.listen(3000, () => console.log('π Server running on port 3000'));
Replace
localhost:27017
with your MongoDB Atlas URI if using cloud π
π§± Define a Schema (Structure of Data)
jsCopyEditconst UserSchema = new mongoose.Schema({
name: String,
email: String,
});
const User = mongoose.model('User', UserSchema);
This creates a users
collection in MongoDB automatically π§
π CRUD Operations in MongoDB with Mongoose
β Create (POST)
jsCopyEditapp.post('/users', async (req, res) => {
const user = await User.create(req.body);
res.status(201).json(user);
});
π Read (GET)
jsCopyEditapp.get('/users', async (req, res) => {
const users = await User.find();
res.status(200).json(users);
});
π οΈ Update (PUT)
jsCopyEditapp.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
res.json(user);
});
β Delete (DELETE)
jsCopyEditapp.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({ message: "User deleted!" });
});
π§ͺ Test it using Postman or VSCodeβs Thunder Client!

(Insert visual showing the flow from frontend β Express routes β Mongoose β MongoDB)
β‘ Now Letβs Talk SQL β Node.js + PostgreSQL/MySQL
SQL databases are great when you need relationships, transactions, and structured data.
Letβs use Prisma as our ORM to work with SQL easily.
π§ Step-by-Step: Use PostgreSQL with Prisma
π§± 1. Install Prisma
bashCopyEditnpm install prisma --save-dev
npx prisma init
Update .env
with your DB URL:
envCopyEditDATABASE_URL="postgresql://user:password@localhost:5432/mydb"
π 2. Define a Model
prismaCopyEdit// prisma/schema.prisma
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}
βοΈ 3. Push to DB
bashCopyEditnpx prisma migrate dev --name init
π§βπ» CRUD with Prisma in Express
jsCopyEditconst { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
Create
jsCopyEditapp.post('/users', async (req, res) => {
const user = await prisma.user.create({ data: req.body });
res.json(user);
});
Read
jsCopyEditapp.get('/users', async (req, res) => {
const users = await prisma.user.findMany();
res.json(users);
});
Update
jsCopyEditapp.put('/users/:id', async (req, res) => {
const user = await prisma.user.update({
where: { id: parseInt(req.params.id) },
data: req.body
});
res.json(user);
});
Delete
jsCopyEditapp.delete('/users/:id', async (req, res) => {
await prisma.user.delete({ where: { id: parseInt(req.params.id) } });
res.json({ message: "Deleted!" });
});
π‘ ORMs Like Prisma and Sequelize β Why Use Them?
- π Write JS code, not raw SQL
- β‘ Auto-generate models and types
- β Validate data easily
- π Manage relationships
Other ORMs:
- Sequelize (most popular)
- Drizzle ORM (lightweight and TS-first)

π Bonus Tips
- π¦ Use
.env
files to hide credentials - π Always validate input (e.g., with
zod
orjoi
) - π§ͺ Write tests for DB logic
π§ Recap Time!
βοΈ What databases are
βοΈ Difference between SQL & NoSQL
βοΈ CRUD with MongoDB & Mongoose
βοΈ CRUD with PostgreSQL & Prisma
βοΈ How to use ORMs in real apps
π Next Step? Build a Real Project!
How about a simple Blog API or Todo App with MongoDB and Express?
Want me to build one in the next article? π
π Follow Web Codder & Learn More!
π₯ Subscribe to our YouTube for step-by-step tutorials:
π₯ Web Codder YouTube Channel
πΈ Join us on Instagram:
π @web_codder_official
π¬ Get dev tips directly on WhatsApp:
π webcodder.dev/whatsapp