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