Chapter 3: Databases
If a web server loses power, any data stored in its RAM is instantly destroyed. To make data permanent (like user accounts and passwords), you must connect your server to a Database. Databases are highly optimized systems designed to store, retrieve, and search massive amounts of data in milliseconds.
SQL (Relational Databases)
SQL (Structured Query Language) databases are the gold standard. Examples include PostgreSQL and MySQL. They store data in strict, rigid Tables (like an Excel spreadsheet) with rows and columns.
- Strict Schemas: If your "Users" table requires an email, a password, and an age, you cannot insert a user without those exact fields.
- Relations: You can link tables together using "Foreign Keys". E.g., User ID #5 in the Users table is linked to Order ID #102 in the Orders table.
-- A standard SQL query to fetch data
SELECT username, email FROM users
WHERE age > 18
ORDER BY created_at DESC;
NoSQL (Non-Relational Databases)
NoSQL databases (like MongoDB) are much more flexible. Instead of rigid tables, they store data as "Documents" (which look exactly like JSON objects). This is incredibly popular in the Node.js ecosystem.
- Flexibility: You can save a user with an email and password, and the next user with an email, password, and a list of 5 favorite movies. The database doesn't care.
- Speed: Often faster for massive, unstructured data dumps, but harder to perform complex relational queries.
SQL Injection Warning
Never take raw input from a user (like a search bar) and paste it directly into a database query. Hackers will input malicious SQL commands (like DROP TABLE users;) and permanently delete your database. Always use ORMs or Parameterized Queries.
Mini Task: Setup MongoDB Atlas
- Go to MongoDB.com and sign up for an Atlas account.
- Create a Free Tier cluster (a database hosted in the cloud for free).
- Get your connection string. You will need this to connect your backend code to the database!