Nestjs中操作mysql数据库可以使用Nodejs封装的DB库,也可以使用TypeORM。下面我们主要给大家讲讲在Nestjs中使用TypeORM操作mysql数据库
TypeORM是一个ORM框架,是一款比较成熟的对象关系映射器,它是由typescript写的。 支持 MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL等数据库。
Nest 操作Mysql官方文档:https://docs.nestjs.com/techniques/database
npm install --save @nestjs/typeorm typeorm mysql
在app.module.ts中配置数据库连接
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type: 'mysql', host: 'localhost', port: 3306, username: 'root', password: 'root', database: 'test', entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), ], }) export class AppModule {}
import { PrimaryGeneratedColumn, Column, Entity } from "typeorm"; @Entity() export class Nav { @PrimaryGeneratedColumn() id: number; @Column({length: 45}) name: string; @Column({length:255}) url: string; @Column('int') status: number; }
import { Module } from '@nestjs/common'; import { UserController } from './controller/user/user.controller'; import { NewsController } from './controller/news/news.controller'; import { TypeOrmModule } from '@nestjs/typeorm'; import {Nav} from '../../entity/nav.entity'; import {Navinfo} from '../../entity/navinfo.entity'; import { AppService } from '../../app.service'; @Module({ imports:[TypeOrmModule.forFeature([Nav,Navinfo])], controllers: [UserController, NewsController], providers:[AppService] }) export class AdminModule {}
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import {Nav} from './entity/nav.entity'; import {Navinfo} from './entity/navinfo.entity'; @Injectable() export class AppService { constructor( @InjectRepository(Nav) private readonly navRepository: Repository