Getting started with Nest.js-connect to the database
In order to connect to the database in Nestjs, the @nestjs/typeorm package is provided
If it is not installed before use, you need to install it.The installation command is as follows
npm install --save @nestjs/typeorm typeorm mysql
MySQL is used here, of course TypeORM also supports other relational databases, such as PostgreSQL, Oracle, Microsoft SQL Server, and NoSQL databases such as MongoDB
If TypeORM is installed successfully, you can import TypeOrmModule
import {TypeOrmModule} from'@nestjs/typeorm';
How to configure MySQL parameters (such as connected database address, user name, password, database)
import {Module} from'@nestjs/common'; import {TypeOrmModule} from'@nestjs/typeorm'; import {AppController} from'./app.controller'; import {AppService} from'./app.service'; @Module({ imports: [ TypeOrmModule.forRoot({ type:'mysql', host: '127.0.0.1', port: 3306, username:'root', password: '123456', database:'test', entities: [], synchronize: true, }) ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
The forRoot method provides all the configuration parameters to the createConnection method of the TypeORM package.In addition, there are some other configuration parameter properties as follows
retryAttempts: default 10, the number of attempts to connect to the database
retryDelay: The default is 3000, the delay time when trying to connect to the database
autoLoadEntities: default false, if true, entities will be automatically loaded
keepConnectionAlive: default false, if true, the connection will not be closed when the application is closed
After the database configuration connection is normal, it can be used normally
The complete code of app.module.ts is as follows
import {Module} from'@nestjs/common'; import {TypeOrmModule} from'@nestjs/typeorm'; import {AppController} from'./app.controller'; import {AppService} from'./app.service'; import {Connection} from'typeorm'; @Module({ imports: [ TypeOrmModule.forRoot({ type:'mysql', host: '127.0.0.1', port: 3306, username:'root', password: '123456', database:'test', entities: [], synchronize: true, logging: true, }), ], controllers: [AppController], providers: [AppService], }) export class AppModule { constructor(private connection: Connection) {} }
How to connect to the database to query and add
Create Entity
cats/cats.entities.ts code is as follows
import {Entity, Column, PrimaryGeneratedColumn} from'typeorm'; @Entity({ name:'cats' }) export class Cats { @PrimaryGeneratedColumn() id: number; @Column({ name:'first_name' }) firstName: string; @Column({ name:'last_name' }) lastName: string; @Column({ name:'is_active', default: true }) isActive: boolean; }
Create Service
cats/cats.service.ts code is as follows
import {Injectable} from'@nestjs/common'; import {InjectRepository} from'@nestjs/typeorm'; import {Repository} from'typeorm'; import {Cats} from'./cats.entity'; @Injectable() export class CatsService { constructor( @InjectRepository(Cats) private catsRepository: Repository<Cats>, ) {} findAll(): Promise<Cats[]> { return this.catsRepository.find(); } findOne(id: number): Promise<Cats> { return this.catsRepository.findOne(id); } async remove(id: number): Promise<void> { await this.catsRepository.delete(id); } async create(cats: Cats): Promise<void> { await this.catsRepository.save(cats); } }
Create Controller
cats/cats.controller.ts
import {Body, Controller, Get, Post, Res} from'@nestjs/common'; import {Response} from'express'; import {Cats} from'./cats.entity'; import {CatsService} from'./cats.service'; @Controller('cats') export class CatsController { constructor(private readonly catsService: CatsService) {} @Get('/index') index(@Res() res: Response): string { this.catsService.findAll(); var cats: Promise<Cats[]> = this.catsService.findAll(); cats .then((data) => { return res.render('cats/index', { message:'Cats', data: data, }); }) .catch((error) => { console.log(error); }); return''; } @Post('/create') async create(@Body() catsParam: {firstName: string; lastName: string }) { let cats = new Cats(); cats.firstName = catsParam.firstName; cats.lastName = catsParam.lastName; cats.isActive = true; return await this.catsService.create(cats); } }
Create Module
cats/cats.module.ts
import {Module} from'@nestjs/common'; import {TypeOrmModule} from'@nestjs/typeorm'; import {CatsController} from'./cats.controller'; import {Cats} from'./cats.entity'; import {CatsService} from'./cats.service'; @Module({ imports: [TypeOrmModule.forFeature([Cats])], controllers: [CatsController], providers: [CatsService], }) export class CatsModule {}
Modify AppModule
app.module.ts
import {Module} from'@nestjs/common'; import {TypeOrmModule} from'@nestjs/typeorm'; import {AppController} from'./app.controller'; import {AppService} from'./app.service'; import {CatsModule} from'./cats/cats.module'; import {Connection} from'typeorm'; import {Cats} from'./cats/cats.entity'; @Module({ imports: [ TypeOrmModule.forRoot({ type:'mysql', host: '127.0.0.1', port: 3306, username:'root', password: '123456', database:'test', entities: [Cats], synchronize: true, logging: true, }), CatsModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule { constructor(pr ivate connection: Connection) {} }
Run the project
npm run start:dev
After startup, if the table does not exist, the table cats will be created automatically
After normal startup, there is no problem, first create a data
curl -d'firstName=cats&lastName=1''http://localhost:3000/cats/create'
Then visit http://localhost:3000/cats/index
You will see the created data output
0 Comments