使用nestjs和typeorm连接数据库

引入typeorm 和 mysql

npm install @nestjs/typeorm typeorm mysql

创建Module cats

nest g mo cats
nest g co cats
nest g s cats

在AppModule里引入TypeormModule

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsModule } from './cats/cats.module';


@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'password',
      database: 'nest',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
    CatsModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  constructor (private readonly connection: Connection) {} 
}

配置cats类Module

Typeorm可以利用entity的实例,自动生成数据库表单。
cats.entity.ts

import{ PrimaryGeneratedColumn, Column, Entity } from "typeorm";
import { ColumnMetadata } from "typeorm/metadata/ColumnMetadata";

@Entity()
export class Cats {
    @PrimaryGeneratedColumn() 
    id: number;
    
    @Column({length: 45})
    name: string;

    @Column('int')
    age: number;
} 

typeorm生成的表单也可以储存到文件里

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

@Injectable()
export class CatsService {
    constructor(

        @InjectRepository(Cats)
        private readonly catsRepository : Repository<Cats>

    ) {}

    async find(){
        return await this.catsRepository.find();
    }
}

然后在cats.module.ts引入typeorm的module类

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm'
import { Cats } from './cats.entity';
import { CatsService } from './cats.service';
import { CatsController } from './cats.controller';

@Module({
  imports: [TypeOrmModule.forFeature([Cats])],
  providers: [CatsService], 
  controllers: [CatsController]
})
export class CatsModule {}

此时已经可以连接数据库了,为了测试是否能连接数据库配置一下cats的控制器

cats.controller.ts

import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';
import { Repository } from 'typeorm';
import { Cats } from './cats.entity';
import { promises } from 'dns';

@Controller('cats')
export class CatsController {
    constructor(private readonly catService: CatsService) {}

    @Get()
    getfind(): Promise<Cats[]> {
        return this.catService.find();
    }
}

然后就可以看到输出了一个[]因为此时数据库空。
所以第一次连接数据库就成功了。

你可能感兴趣的:(后端开发)