Learn to interact with relational and NoSQL databases using TypeORM and Prisma.
Welcome to the TypeORM Deep Dive chapter! In this section, we'll explore how to connect your NestJS application with a PostgreSQL database using TypeORM. You'll learn about defining entities, running migrations, and managing relationships between database tables.
TypeORM is a popular ORM (Object-Relational Mapping) tool for TypeScript and JavaScript applications. It allows you to define your database schema using classes (entities) and provides tools for querying, managing relationships, and performing migrations.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from 'typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'your_user',
password: 'your_password',
database: 'nestjs_db',
entities: ['dist/entities/**/*.js'],
synchronize: false
})
]
})
export class DatabaseModule {}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({
unique: true,
length: 255
})
email: string;
@Column({
nullable: false
})
username: string;
TypeORM supports various relationship types including one-to-one, one-to-many, and many-to-many. Let's explore how to define these relationships.
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column()
content: string;
@ManyToMany(() => Tag)
tags: Tag[];
Understand the difference between eager loading (loading all relationships at once) and lazy loading (loading relationships on demand). Use these strategies to optimize your application's performance.
const post = await getRepository(Post)
.createQueryBuilder('post')
.leftJoinAndSelect('post.tags', 'tags')
.where('post.id = :id', { id: 1 })
.getOne();
Learn how to manage database transactions for consistency and reliability. Use transactions when performing operations that must succeed or fail as a single unit.
const transaction = await dataSource.createTransaction();
try {
// Perform your database operations
await transaction.commit();
} catch (error) {
await transaction.rollback();
}
Welcome to the world of modern database querying with Prisma! If you've ever worked with TypeORM or other ORMs and felt limited by their capabilities, Prisma is here to change your perspective. In this chapter, we'll explore how to set up Prisma in your NestJS project, model your database schema using the powerful Prisma schema language, and perform sophisticated database operations using the generated Prisma client.
To integrate Prisma into your NestJS project, follow these steps:
npx prisma init
Prisma uses the Prisma schema language to define your database models. This schema-driven approach allows you to generate both the database schema and client code from a single source of truth.
// prisma/schema.prisma
database 'mysql' {
url = env('DATABASE_URL')
schema = 'public'
}
model User {
id Int @id
email String @unique
name String
posts Post[]
}
model Post {
id Int @id
title String
content String
author User @relation(fields: [authorId], references: [id])
authorId Int
}
Prisma's query builder provides a consistent API for performing CRUD operations on your models.
// Create
const user = await prisma.user.create({
data: {
email: 'john.doe@example.com',
name: 'John Doe'
}
});
// Read
const users = await prisma.user.findMany({
where: {
email: { contains: 'example' }
},
orderBy: {
name: 'asc'
}
});
// Update
const updatedUser = await prisma.user.update({
where: { id: 1 },
data: { name: 'Jane Doe' }
});
// Delete
const deletedUser = await prisma.user.delete({
where: { id: 1 }
});
Prisma makes it easy to work with relationships between models.
// One-to-Many
const userWithPosts = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true
}
});
// Many-to-Many
const userWithRoles = await prisma.user.findUnique({
where: { id: 1 },
include: {
roles: true
}
});
Prisma comes with a suite of tools to help you visualize and interact with your database.
Question 1 of 12