Skip to main content

Day 35 – Complete CRUD with MySQL (Node.js + Express)

Updated 6 min readMarkdown

Mini Project Start: 💰 Money Tracker


Day 35 Goal

By the end of Day 35, students will be able to:

✅ Perform complete CRUD with MySQL
✅ Create Update & Delete APIs
✅ Handle errors properly (best practices)
✅ Start a real-life mini project – Money Tracker
✅ Understand industry-style backend flow


🔁 Quick Recap (Till Day 34)

Till now, students already know:

  • MySQL basics

  • Tables & SQL queries

  • phpMyAdmin CRUD

  • Node.js + Express

  • Connecting MySQL with Node using mysql2

  • GET & POST APIs

👉 Today we complete CRUD and start a real project


🧠 What is CRUD? (Very Simple)

CRUD means basic database operations:

Operation

Meaning

SQL

C

Create

INSERT

R

Read

SELECT

U

Update

UPDATE

D

Delete

DELETE

👉 Any real application = CRUD


💰 Mini Project: Money Tracker (Real-Life Example)

Real life use case:

You want to track:

  • Income 💵

  • Expense 💸

  • Amount

  • Description

Just like:

  • Personal expense app

  • Office finance tracker

  • Daily spending record


📂 Project Folder Structure (Professional)

money-tracker/
│
├── config/
│   └── db.js
│
├── controllers/
│   └── transactionController.js
│
├── routes/
│   └── transactionRoutes.js
│
├── app.js
├── package.json

👉 Same structure used in real companies


🗄️ Database Design (MySQL)

Database name:

money_tracker

Table name:

transactions

Table structure:

Column

Type

id

INT (Primary Key, Auto Increment)

title

VARCHAR

amount

INT

type

ENUM ('income','expense')


🔌 Database Connection (db.js)

📄 config/db.js

const mysql = require("mysql2");

const db = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "money_tracker",
});

db.connect((err) => {
  if (err) {
    console.log("Database connection failed ❌");
    return;
  }
  console.log("MySQL Connected ✅");
});

module.exports = db;

🚀 Express Server Setup

📄 app.js

const express = require("express");
const app = express();

const transactionRoutes = require("./routes/transactionRoutes");

app.use(express.json());

app.use("/transactions", transactionRoutes);

app.listen(3000, () => {
  console.log("Server running on port 3000 🚀");
});

🧠 Controller – Business Logic

📄 controllers/transactionController.js

1️⃣ CREATE – Add Transaction

const db = require("../config/db");

exports.addTransaction = (req, res) => {
  const { title, amount, type } = req.body;

  if (!title || !amount || !type) {
    return res.status(400).json({ message: "All fields are required" });
  }

  const query =
    "INSERT INTO transactions (title, amount, type) VALUES (?, ?, ?)";

  db.query(query, [title, amount, type], (err) => {
    if (err) {
      return res.status(500).json({ message: "Failed to add transaction" });
    }
    res.json({ message: "Transaction added successfully ✅" });
  });
};

2️⃣ READ – Get All Transactions

exports.getTransactions = (req, res) => {
  const query = "SELECT * FROM transactions";

  db.query(query, (err, results) => {
    if (err) {
      return res.status(500).json({ message: "Failed to fetch data" });
    }
    res.json(results);
  });
};

3️⃣ UPDATE – Update Transaction

exports.updateTransaction = (req, res) => {
  const { id } = req.params;
  const { title, amount } = req.body;

  const query =
    "UPDATE transactions SET title=?, amount=? WHERE id=?";

  db.query(query, [title, amount, id], (err, result) => {
    if (err) {
      return res.status(500).json({ message: "Update failed" });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: "Transaction not found" });
    }

    res.json({ message: "Transaction updated ✅" });
  });
};

4️⃣ DELETE – Delete Transaction

exports.deleteTransaction = (req, res) => {
  const { id } = req.params;

  const query = "DELETE FROM transactions WHERE id=?";

  db.query(query, [id], (err, result) => {
    if (err) {
      return res.status(500).json({ message: "Delete failed" });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: "Transaction not found" });
    }

    res.json({ message: "Transaction deleted ✅" });
  });
};

🛣️ Routes

📄 routes/transactionRoutes.js

const express = require("express");
const router = express.Router();

const {
  addTransaction,
  getTransactions,
  updateTransaction,
  deleteTransaction,
} = require("../controllers/transactionController");

router.post("/", addTransaction);
router.get("/", getTransactions);
router.put("/:id", updateTransaction);
router.delete("/:id", deleteTransaction);

module.exports = router;

🧪 API Testing (Postman)

➕ Add Transaction

POST /transactions
{
  "title": "Salary",
  "amount": 30000,
  "type": "income"
}

📥 Get All Transactions

GET /transactions

✏ Update Transaction

PUT /transactions/1
{
  "title": "Groceries",
  "amount": 2500
}

❌ Delete Transaction

DELETE /transactions/1

⚠️ Error Handling Best Practices (Very Important)

✔ Always check missing data

✔ Always handle DB errors

✔ Always check affectedRows

✔ Return proper HTTP status codes

✔ Never crash server

👉 This is professional backend practice


🧠 Why This Project Is Important?

✔ Covers full CRUD

✔ Real-world logic

✔ Proper structure

✔ MySQL + Node integration

✔ Interview-ready project


📝 Student Practice Tasks

Task 1

Add API to fetch only income transactions

Task 2

Add API to fetch only expenses

Task 3

Add total income & expense calculation API


🎯 Interview Questions (Day 35)

  1. What is CRUD?

  2. Difference between PUT and POST?

  3. Why use affectedRows?

  4. How do you handle errors in Node.js?

  5. MySQL vs MongoDB – when to use?


🔔 Stay Connected

If you found this article helpful and want to receive more such beginner-friendly and industry-relevant Node JS notes, tutorials, and project ideas — 📩 Subscribe to our newsletter by entering your email below.

And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment, 🎥 Don’t forget to subscribe to my YouTube channel – Knowledge Factory 22 – for regular content on tech concepts, career tips, and coding insights!

Stay curious. Keep building. 🚀

About the author

  • Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: 🚀 In-depth explorations of emerging technologies 💡 Practical tutorials and how-to guides 🔧Insights on software development best practices 🚀Reviews of the latest tools and frameworks 💡 Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Let’s connect and grow together! 🌟

No comments yet. Be the first to comment.