Databases Introduction in Node
Introduction
Persistent apps store data in databases—PostgreSQL, MySQL, MongoDB, Redis, and others. Node does not include a database engine; you install a driver or ORM and connect over the network or local socket. This chapter explains concepts and a minimal PostgreSQL-style flow without binding you to one vendor.
Prerequisites
SQL vs Document Stores (Brief)
| Style | Examples | Shape |
|---|---|---|
| Relational (SQL) | PostgreSQL, MySQL, SQLite | Tables, rows, JOINs |
| Document | MongoDB | JSON-like documents |
| Key-value / cache | Redis | Strings, hashes, TTL |
Choose based on data relationships, team skills, and ops constraints.
Connection String in Env
DATABASE_URL=postgres://user:pass@localhost:5432/myappNever commit real credentials—use .env locally and secrets in production.
Raw SQL with pg (Conceptual)
npm install pg$1 placeholders prevent SQL injection—never interpolate user strings into SQL.
ORM Example Sketch (Prisma-style)
ORMs map tables to JavaScript objects and generate migrations:
// Pseudocode — actual API depends on library
// const user = await prisma.user.create({ data: { email, name } });Good for rapid development; learn SQL fundamentals anyway.
MongoDB Sketch
// Conceptual — mongodb driver
// const doc = await collection.findOne({ email });
// await collection.insertOne({ email, name, createdAt: new Date() });Flexible schema; enforce shape in application code or JSON Schema.
Redis for Cache
// Cache expensive query result 60 seconds
// await redis.set(`user:${id}`, JSON.stringify(user), "EX", 60);
// const cached = await redis.get(`user:${id}`);Not a replacement for primary storage—cache and session store use cases.
Transactions (SQL)
Mini Example: In-Memory Repo (Tests)
Swap implementation behind the same functions when adding PostgreSQL.
FAQ
SQLite for learning?
Yes—single file, zero server—great for local tutorials and tests.
Connection pooling?
Reuse pools (pg.Pool)—opening a connection per request is slow.
Migrations?
Version schema with SQL migration files or ORM tools—never edit production tables by hand without a plan.
What comes next?
Course wrap-up, then async/await and message queues.