Connecting to a Database

Node apps store data in databases through driver packages.

Syntaxconst rows = await db.query('SELECT * FROM users');

Real apps need to store data permanently. Node connects to databases through driver or ORM packages installed from npm.

Common choices

  • PostgreSQL / MySQL — relational, using pg or mysql2.
  • MongoDB — document database, using mongodb or mongoose.
  • SQLite — a lightweight file-based database.

The pattern is similar everywhere: connect, run a query, use the results — usually with async/await.

Example

Example · javascript
// Conceptual example with the 'pg' PostgreSQL client
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function getUsers() {
  const result = await pool.query('SELECT id, name FROM users');
  console.log(result.rows);
}
getUsers();

When to use it

  • A todo-list API uses the `pg` module to store and retrieve tasks from PostgreSQL, keeping data persistent across server restarts.
  • An analytics service writes high-frequency event data to MongoDB via the `mongodb` driver because its flexible schema suits variable event shapes.
  • A developer uses an in-process SQLite database via `better-sqlite3` for a lightweight CLI tool that needs persistence without a separate database server.

More examples

Connect to PostgreSQL with pg

Creates a connection pool with `pg` and queries PostgreSQL using async/await -- the standard Node.js pattern.

Example · js
const { Pool } = require('pg');

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

async function getUsers() {
  const { rows } = await pool.query('SELECT id, name FROM users LIMIT 10');
  return rows;
}

getUsers().then(console.log);

Parameterized query to prevent SQL injection

Uses parameterized queries (`$1`) to pass user input safely, preventing SQL injection attacks.

Example · js
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL });

async function getUserById(id) {
  const { rows } = await pool.query(
    'SELECT * FROM users WHERE id = $1',
    [id]  // second arg -- the values array
  );
  return rows[0];
}

getUserById(42).then(console.log);

Connect to MongoDB with the driver

Uses the official MongoDB Node.js driver to connect, query a collection, and close the connection.

Example · js
const { MongoClient } = require('mongodb');

async function main() {
  const client = new MongoClient(process.env.MONGO_URL);
  await client.connect();
  const db    = client.db('shop');
  const items = await db.collection('products').find({}).limit(5).toArray();
  console.log(items);
  await client.close();
}
main();

Discussion

  • Be the first to comment on this lesson.