Class 04: Kết nối Database với TypeORM
Cấu hình kết nối cơ sở dữ liệu PostgreSQL/MySQL với TypeORM
Cài đặt package
npm install --save @nestjs/typeorm typeorm pgnpm install --save @nestjs/typeorm typeorm mysql2Cấu hình TypeORM module
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UsersModule } from './users/users.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres', // hoặc 'mysql'
host: 'localhost',
port: 5432, // với MySQL là 3306
username: 'postgres', // hoặc 'root' với MySQL
password: 'password',
database: 'testdb',
autoLoadEntities: true,
synchronize: true, // chỉ dùng trong phát triển, KHÔNG dùng production
}),
UsersModule,
],
})
export class AppModule {}Giải thích các tuỳ chọn
Tạo Entity và Repository
Tạo Entity User
UserĐăng ký Entity vào Module
Sử dụng Repository trong Service
Migration cơ bản với TypeORM CLI
Cài đặt CLI
Tạo và chạy migration
Bài tập thực hành
Mục tiêu
Yêu cầu
Gợi ý
PreviousClass 03: Service và Data ValidationNextClass 05: Quan hệ trong Database (OneToMany, ManyToOne) với TypeORM
Last updated