文章问题导向

在nest中,如何使用typeorm连接mysql数据库?
如何连接多个数据库?

如果你都有了答案,可以忽略本文章,或去nest学习导图寻找更多答案


第一步:安装相关依赖

yarn add typeorm @nestjs/typeorm mysql

以及创建相关文件

src -> module -> user

user.module.ts
user.service.ts
user.controller.ts
user.entity.ts

第二步:引入并配置数据库,连接数据库
在app.module.ts的imports中,使用TypeOrmModule引入mysql配置

app.module.ts

import {Module} from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@module({
    imports: [
        TypeOrmModule.forRoot({
        	name:'mydatabase',
            type:'mysql',
            host:'localhost',
            port: 3306,
            username: 'root',
            password: 'root',
            database: 'test',
            entities: [__dirname + '/**/*.entity{.ts,.js}'],
            synchronize: true    
        })
    ]
})
export class AppModule{}

第三步:创建数据库实体

实体:也就是数据库表,具体设计:请学习typeorm教程
nest启动时,会自动创建该数据表

user.entity.ts

import {
  Column,
  Entity,
  PrimaryGeneratedColumn,
  OneToMany,
  OneToOne,
  JoinColumn,
} from 'typeorm';
import { PhotoEntity } from '../photo/photo.entity';

@Entity({ name: 'user' })  //数据表的名字
export class UsersEntity {
  @PrimaryGeneratedColumn() //设置主键和自增
  id: number;

  @Column({ length: 12 }) //字段及相关限制
  username: string;

  @Column({ length: 32, select: false })
  password: string;

  @Column({ default: 1 })
  status: number;

  //一对多关系
  @OneToMany(() => PhotoEntity, (photo) => photo.user)
  photos: [];
}

第四步:在需要使用实体的module中注册实体

user.module.ts

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { UsersEntity } from './user.entity';

@Module({
  imports: [TypeOrmModule.forFeature([UsersEntity])], //注入实体,可注入多个实体,是数组
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule { }

第五步:在controller注入service
service模块,专用于操作数据库,controller负责逻辑

import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
} from '@nestjs/common';
import { ResInterface } from '../../interface/response.interface';
import { UserService } from './user.service';
import { UsersEntity } from './user.entity';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { } //注入service

  //逻辑:当请求user时匹配路径和接口方法,命中则异步调用service定义好的方法,等待返回的结果再进一步处理
  @Get()
  async findAll(): Promise<ResInterface> {
    return await this.userService.findAll(); //异步调用service定义好的方法
  }

  @Get(':id')
  async getUserById(@Param('id') id: string): Promise<ResInterface> {
    return await this.userService.getUserById(id);
  }
}

第六步:在seriver注入实体,真正查询数据库的地方
使用InjectRepository注入数据库实体,即可使用数据库的查询方法,更多详情请学习typeorm教程

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

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UsersEntity)  //注入数据库实体
    private readonly usersRepository: Repository<UsersEntity>
  ) { }

  async findAll(): Promise<any> {
    return await this.usersRepository.findAndCount(); //调用数据的查询方法
  }

  async getUserById(id: string): Promise<UsersEntity> {
    const await this.usersRepository.findOne(id);
  }
}

接下来就可以使用 postman 来测试啦


如何连接多个数据库?

第一步:连接多个数据库
@moduel({
    imports:[
        TypeOrmModule.forRoot({
            name:database1, //使用name属性
            ...
        }),
        TypeOrmModule.forRoot({
            name:database2,
            ...
        })
    ]
})


第二步:使用时加入参数:声明使用的数据库
@Module({
  imports: [TypeOrmModule.forFeature([UsersEntity], 'database1')],  
  controllers: [UserController],
  providers: [UserService],
})


第三步:在service注入时
constructor(
    @InjectRepository(UsersEntity, 'database1')
    private readonly usersRepository: Repository<UsersEntity>
) {}

学习更多

nest学习导图

更多推荐