In this app, we will create an API to add, update, and delete notes. We will send requests from Postman in JSON format, and the notes will be stored in an empty array.

// Import the Express module
const express = require('express');

// Create an Express app instance
const app = express();

// Middleware to parse incoming JSON data from requests
// This makes data available in req.body for POST, PATCH, etc.
// We will learn more about this topic later
app.use(express.json());

// In-memory array to store notes
let notes = [];

// ===============================
// Route to CREATE a new note
// ===============================
app.post("/notes", (req, res) => {
  // Push the note (JSON with title and content) into the array
  notes.push(req.body);

  // Respond with a success message
  res.json({ message: "Note created succesfully." });
});

// ===============================
// Route to UPDATE an existing note by index
// ===============================
app.patch("/notes/:index", (req, res) => {
  // Get the index from the URL parameter
  const index = req.params.index;

  // Destructure title and content from the request body
  const { title, content } = req.body;

  // Update the note at the specified index
  notes[index].title = title;
  notes[index].content = content;

  // Respond with a success message
  res.json({ message: "Updated Sucessfully." });
});

// ===============================
// Route to DELETE a note by index
// ===============================
app.delete("/notes/:index", (req, res) => {
  // Get the index from the URL parameter
  const index = req.params.index;

  // Delete the note at the specified index
  // WARNING: 'delete' leaves an empty spot (undefined) in the array
  delete notes[index];

  // Respond with a success message
  res.json({ message: "Note deleted succesfully." });
});

// ===============================
// Route to GET (view) all notes
// ===============================
app.get("/", (req, res) => {
  // Return all notes (including deleted ones as 'undefined')
  res.json(notes);
});

// ===============================
// Start the server on port 3000
// ===============================
app.listen(3000, () => {
  console.log("server is running on port 3000.");
});


๐Ÿ’พ Why Data Gets Lost on Server Restart

Right now, in your Express app, youโ€™re storing notes in this line:


let notes = [];

This is just a temporary variable in memory (RAM). That means:


๐Ÿ—„๏ธ Why You Need a Database

A database stores data permanently, unlike in-memory storage.

โœ… Benefits of a database:


๐Ÿ”Œ Common Databases You Can Use with Node.js

Type Examples Description
SQL MySQL, PostgreSQL Structured tables, rows, columns
NoSQL MongoDB, Firebase JSON-like format, flexible structure
File-based JSON files (basic use) Not scalable, but simple