Connecting a database: TypeORM
Until now posts lived in an array and vanished on restart. Now let us connect a database. TypeORM is an ORM library: it links TypeScript classes to tables and lets you work with rows as objects without writing SQL by hand. The @nestjs/typeorm package plugs it into NestJS modules.
Installation
The course uses SQLite: the whole database is one file in the project folder, no separate server needed.
npm i @nestjs/typeorm typeorm better-sqlite3better-sqlite3 is the driver TypeORM uses to talk to the SQLite file. For PostgreSQL you install pg instead, and mysql2 for MySQL.
Connecting in the root module
The database file path is already in .env (the DB_PATH variable), so the connection reads it through ConfigService:
// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostsModule } from './posts/posts.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync({
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
type: 'better-sqlite3',
database: config.get<string>('DB_PATH', 'blog.sqlite'),
autoLoadEntities: true,
synchronize: true,
}),
}),
PostsModule,
],
})
export class AppModule {}forRootAsync() delays the setup until ConfigService is ready: inject lists the needed services, and useFactory receives them and returns the connection options. Run npm run start:dev — a blog.sqlite file appears in the project root, and the terminal shows TypeOrmCoreModule dependencies initialized.
Connection options
| Option | Meaning |
|---|---|
type | Which database: better-sqlite3, postgres, mysql |
database | Database name; for SQLite, the file path |
autoLoadEntities | Find table classes from modules automatically |
synchronize | Create and alter tables from classes on every start |
For PostgreSQL you add host, port, username and password — also taken from .env.
What synchronize does
With synchronize: true TypeORM compares entity classes with tables and brings the database in line itself: it adds tables and columns. For a learning project that is convenient — no SQL to write. But when you rename a field TypeORM may drop the column together with its data, so on a production server this mode is turned off and migrations are used instead — files that describe database changes.
Checking
There are no tables in the database yet: TypeORM does not know what data to store. Table classes — entities — are described in the next lesson, and then the tables appear by themselves.
Common mistake
A DriverPackageNotInstalledError at startup means the driver package named in type is not installed. For better-sqlite3 run npm i better-sqlite3. If the package is installed and the error persists, delete node_modules and run npm install — the driver is built for your Node.js version.