Lesson 6 / 35
Setting Up TypeORM
Configure a TypeORM DataSource, write decorated entity classes and initialise the connection before querying.
By Rahul Agarwal · 15 years in web development
DataSource and entities
TypeORM is configured through a DataSource object. It holds the database type, connection details, the list of entities (decorated classes), migration paths and flags such as synchronize and logging. Nothing talks to the database until you call await dataSource.initialize(), which opens the connection pool and builds metadata from the decorators. TypeORM relies on TypeScript's legacy decorators and runtime type metadata, so the project needs experimentalDecorators and emitDecoratorMetadata enabled in tsconfig.json and the reflect-metadata package imported once at startup. A frequent beginner mistake is calling a repository before initialize() resolves, which fails because the metadata is not ready. Another is leaving synchronize: true on in production: it alters tables automatically on startup and can drop data when a column is renamed. Use it for quick experiments only and switch to migrations for anything real.
Entity and DataSource
The ! tells TypeScript the ORM will fill these fields, which keeps strictPropertyInitialization happy.
import 'reflect-metadata';
import { DataSource, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id!: number;
@Column({ unique: true })
email!: string;
@Column()
name!: string;
}
export const AppDataSource = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [User],
synchronize: false,
logging: true,
});Initialise, then query
create builds an entity instance in memory; save performs the INSERT and fills in the generated id.
await AppDataSource.initialize();
const users = AppDataSource.getRepository(User);
const asha = users.create({ email: 'asha@example.com', name: 'Asha' });
await users.save(asha);
console.log(asha.id);create() does not touch the database
Students often expect repository.create() to insert a row. It only instantiates the entity class. The INSERT happens on save() (or insert()). Mixing them up leads to code that seems to work but never persists anything.
Quick check: Why should synchronize: true be avoided in a production TypeORM DataSource?
- It disables query logging
- It makes every query run inside a transaction
- It only works with SQLite
- It changes the schema automatically on startup and can drop columns or data
Answer
It changes the schema automatically on startup and can drop columns or data — synchronize compares entities with the database and applies changes directly. A rename can look like drop-and-add, losing data. Migrations give you a reviewed, repeatable change instead.