Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 37 ยท Getting Started

Installing and Connecting

Install TypeORM and Sequelize, choose a database driver, create a DataSource or Sequelize instance, test the connection, and see connection settings in a runnable stand-in.

Before any model exists you need three things: the ORM package, a driver for your database, and a connection object. This lesson sets all three up for both libraries and shows what a connection really holds.

The install commands and library code below are read-only. The runnable blocks are stand-ins built on node:sqlite.

Installing

Both ORMs sit on top of a database driver that you install yourself. The driver is the package that speaks the database's wire protocol.

Database Driver package
PostgreSQL pg
MySQL / MariaDB mysql2
SQLite sqlite3 or better-sqlite3
SQL Server tedious (Sequelize) or mssql (TypeORM)
Terminal
# TypeORM (decorators need reflect-metadata)
npm install typeorm reflect-metadata pg
npm install -D typescript @types/node

# Sequelize
npm install sequelize pg pg-hstore

pg-hstore is only needed for PostgreSQL in Sequelize (it serializes the hstore type). For MySQL swap pg for mysql2; the rest of the code stays the same.

Connecting with TypeORM

TypeORM calls the connection a DataSource. You create one, then call initialize() once at start-up.

TypeScript
import "reflect-metadata";
import { DataSource } from "typeorm";

export const AppDataSource = new DataSource({
  type: "postgres",
  host: process.env.DB_HOST ?? "localhost",
  port: 5432,
  username: "app",
  password: process.env.DB_PASSWORD,
  database: "shop",
  entities: [],          // you add entity classes in lesson 3
  synchronize: false,    // never true in production
  logging: ["error"],
});

await AppDataSource.initialize();
console.log("Connected:", AppDataSource.isInitialized);

initialize() opens a connection pool and validates the settings. Reuse the same AppDataSource everywhere; do not create one per request.

Connecting with Sequelize

Sequelize uses one class, Sequelize, for the connection. It is lazy: the object exists immediately and connects when you first query, so call authenticate() to fail early.

TypeScript
import { Sequelize } from "sequelize";

export const sequelize = new Sequelize("shop", "app", process.env.DB_PASSWORD, {
  host: process.env.DB_HOST ?? "localhost",
  dialect: "postgres",
  logging: false,
  pool: { max: 10, min: 0, idle: 10000 },
});

try {
  await sequelize.authenticate();
  console.log("Connection has been established.");
} catch (error) {
  console.error("Unable to connect:", error);
}

You can also pass a connection URL: new Sequelize("postgres://app:secret@localhost:5432/shop"). The dialect option tells Sequelize which SQL flavor to generate.

Side by side

Task TypeORM Sequelize
Connection object new DataSource({...}) new Sequelize(...)
Pick the database type: "postgres" dialect: "postgres"
Connect await ds.initialize() await sequelize.authenticate()
Close await ds.destroy() await sequelize.close()
Pool size extra: { max: 10 } (driver option) pool: { max: 10 }
SQL logging logging: true logging: console.log

A stand-in connection

A connection object is mostly a bag of settings plus a handle. This stand-in validates its options and exposes initialize(), query() and destroy(), like a tiny DataSource over SQLite.

Node.js Stand-in DataSource

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same idea explains the most common start-up bug in real projects: calling a repository before initialize() has finished.

Reading configuration from the environment

Never hard-code passwords. Read them from environment variables and fail loudly when one is missing.

Node.js Config from env

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Troubleshooting connections

  • ECONNREFUSED: the database is not running, or host/port is wrong. In Docker, use the service name, not localhost.
  • password authentication failed: wrong credentials, or the user lacks rights on that database.
  • Please install pg package manually (Sequelize) or a missing driver error (TypeORM): you skipped the driver install.
  • Hanging at start-up: a firewall or SSL requirement. Managed databases often need ssl: true (TypeORM) or dialectOptions: { ssl: {...} } (Sequelize).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does TypeORM call its connection object?

    A DataSource holds the settings and the connection pool; call initialize() once.
  2. 2. Which option tells Sequelize which database flavor to generate SQL for?

    Sequelize uses dialect, while TypeORM uses type.
  3. 3. Why call sequelize.authenticate() at start-up?

    Without it, a bad password only shows up on the first query.
  4. 4. Where should the database password come from?

    Keep secrets out of source code and fail clearly when they are missing.

Summary

  • Install the ORM plus the driver for your database yourself.
  • TypeORM: new DataSource({...}) then await initialize(); Sequelize: new Sequelize(...) then authenticate().
  • Create one connection object and reuse it; both manage a pool.
  • Read credentials from the environment and fail early when they are missing.
  • The stand-in DataSource shows the shape; the real ones add pooling, entities and migrations.

Next: Your First Entity and Model