Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Intermediate

Connecting a database

Data stored in a JavaScript array disappears when the server restarts. Real apps keep data in a database. This lesson uses SQLite through node:sqlite, a database built right into Node.js, and then shows how the same ideas apply to PostgreSQL and MongoDB.

SQLite, built in

SQLite stores a whole database in a single file (or in memory), with no separate server to install. Node 22.5+ includes it as node:sqlite:

Node.js · editable
Method Returns
db.exec(sql) Nothing: runs one or more statements (creating tables)
db.prepare(sql) A prepared statement you can run many times
stmt.run(...params) { changes, lastInsertRowid } for INSERT/UPDATE/DELETE
stmt.get(...params) The first row as an object, or undefined
stmt.all(...params) All rows as an array

Rows come back as plain objects without a prototype, which is why Node prints them as [Object: null prototype]. They behave like normal objects.

If SQL is new to you, the SQL track on this site teaches it from scratch.

Never build SQL from strings

The ? placeholders are essential. Here's why:

Node.js · editable

That's SQL injection, one of the most common and most damaging security bugs. Always pass values as parameters. Named parameters (:email) make longer queries clearer:

js
db.prepare('UPDATE products SET price = :price WHERE id = :id').run({ id: 2, price: 9.49 });

A CRUD API backed by the database

Here's an Express API where each route runs a query. The data-access functions live in their own module, so routes don't contain SQL:

Node.js · editable

Transactions

When several changes must succeed or fail together (moving money, placing an order), wrap them in a transaction:

Node.js · editable

Other databases

The pattern is the same for every database: install a driver, create a connection (or a pool of connections) once at startup, and run parameterised queries.

PostgreSQL with the pg package. Note that queries are asynchronous because the database is another server:

js
import pg from 'pg';

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

const { rows } = await pool.query('SELECT * FROM products WHERE price < $1', [50]);
await pool.query('INSERT INTO products (name, price) VALUES ($1, $2)', ['Mug', 8.99]);

MongoDB with the official mongodb driver:

js
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URL);
const products = client.db('shop').collection('products');

await products.insertOne({ name: 'Mug', price: 8.99, tags: ['kitchen'] });
const cheap = await products.find({ price: { $lt: 50 } }).toArray();

ORMs and query builders

Many teams use a library that maps tables to JavaScript objects and generates SQL:

Library Style
Prisma Schema file + generated, fully typed client (prisma.book.findMany())
Drizzle SQL-like TypeScript query builder
Kysely Type-safe SQL query builder
Mongoose Schemas and models for MongoDB

They save typing and catch mistakes, but learn plain SQL first: every ORM eventually needs it.

Practice

  1. Add a GET /books?author=… filter to the API using a parameterised WHERE author = ?.
  2. Add a reviews table (id, book_id, stars, text) and a POST /books/:id/reviews route.
  3. Write a GET /stats route that returns the number of books and the average year using a single SQL query.
✎ Check your understanding

1.Why use ? placeholders instead of putting values into the SQL string?

2.What does stmt.get() return when no row matches?

3.When do you need a transaction?

← Routing and middleware