likes
comments
collection
share

在 Nest.js 中使用 TypeORM

作者站长头像
站长
· 阅读数 18

在 Nest.js 中使用 TypeORM

在 Nest.js 中,TypeORM 是一种流行的 ORM(对象关系映射)框架,它可以帮助我们创建实体、存储实体、查询实体等。本文将演示如何在 Nest.js 中集成和使用 TypeORM。

安装 TypeORM

在开始之前,我们首先需要安装 TypeORM。在项目根目录下执行以下命令:

npm install typeorm pg

其中 pg 是 Postgres 数据库驱动程序,您可以根据自己的需求安装不同的驱动程序。

创建 TypeORM 配置文件

在项目根目录下创建一个 ormconfig.json 文件,内容如下:

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "postgres",
  "password": "password",
  "database": "nest",
  "entities": ["dist/**/*.entity{.ts,.js}"],
  "synchronize": true
}

其中,type 表示数据库类型,这里我们使用的是 Postgres 数据库,hostport 分别表示数据库服务器的地址和端口号,usernamepassword 分别表示数据库用户名和密码,database 表示数据库名称。entities 表示实体文件的位置,synchronize 表示是否自动同步数据库表结构。

创建实体

在 Nest.js 中,我们可以使用装饰器 @Entity 来标记一个类为实体。下面是一个示例,展示如何创建一个实体:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Cat {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  age: number;
}

在上述示例中,我们定义了一个名为 Cat 的实体,它有一个自增长的主键 id 和两个字段 nameage

注册 TypeORM 模块

在 Nest.js 中,我们需要使用 TypeOrmModule.forRoot() 方法来注册 TypeORM 模块,并传递 ormconfig.json 配置文件路径。下面是一个示例,展示如何在 Nest.js 中注册 TypeORM 模块:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cat } from './cat.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'password',
      database: 'nest',
      entities: [Cat],
      synchronize: true,
    }),
    TypeOrmModule.forFeature([Cat]),
  ],
})
export class AppModule {}

在上述示例中,我们在 AppModule 中注册了 TypeORM 模块,并使用 TypeOrmModule.forRoot() 方法传递 ormconfig.json 配置文件路径。我们还在 TypeOrmModule.forFeature() 方法中传递了 Cat 实体,以便在应用程序中使用该实体。

使用 TypeORM

在 Nest.js 中,我们可以使用 @InjectRepository() 装饰器在其他服务或者控制器中注入 TypeORM 的仓库。下面是一个示例,展示如何在 Nest.js 中使用 TypeORM:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Cat } from './cat.entity';

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cat)
    private readonly catRepository: Repository<Cat>,
  ) {}

  async findAll(): Promise<Cat[]> {
    return this.catRepository.find();
  }
}

在上述示例中,我们在 CatsService 中注入了 Cat 实体的仓库,并使用 findAll() 方法来查询所有猫咪。

总结

在 Nest.js 中,TypeORM 是一种流行的 ORM 框架,它可以帮助我们创建实体、存储实体、查询实体等。在这篇文章中,我们学习了如何在 Nest.js 中集成和使用 TypeORM,以及如何注册 TypeORM 模块和创建实体。

转载自:https://juejin.cn/post/7242202040427348029
评论
请登录