Nestjs links to MySQL to operate data

Neo Luo
5 min readJul 1, 2024

--

Copilot Designer

Preface

Data manipulation is a necessary skill for full-stack or back-end personnel. This chapter mainly explains how to query and add operations to data tables nestjsthrough the TypeORM framework (ORM object-relational mapping). By building an environment, it is convenient for students to quickly build an environmentuser Docker for MySQL

Effect

Create and query data by Postmanviewing the applicationnestjs mysql

Quickly create a nestjs application

Quickly create an application through nestjs CLIscaffolding ( click to see how to quickly create an application ):mysql-nestjs

nest new mysql-nestjs

After successful creation, enter the project and start the application

cd mysql-nestjs
npm run start:dev

Next, start configuringmysql

Docker install mysql

  1. First you need to download Dockerthe application
    Download the installation package for the corresponding system

DockerAfter successful installation, click on the app and you can see Containersthat it is empty.

2. createdocker-compose.yml

Create a configuration file for the container application in the project mysql-nestjsroot directory : and define the service imageDockerdocker-compose.yml

# docker-compose.yml

# Use root/example as user/password credentials
version: '3.1'

services:
db:
image: mysql:8.0
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
MYSQL_DATABASE: testdb
ports:
- 3307:3306

# navicat
adminer:
image: adminer
restart: always
ports:
- 8080:8080

Two images are defined here:

  • mysqlThe default image usernameis root, password is example, and database is:testdb
  • adminerA simple and powerful tool for managing databases, convenient for visualizing data, by localhost:8080accessing the page

3. Start Dockerthe container

Run the command to start in the project mysql-nestjsroot directoryDocker image

docker-compose up -d

-dThe command is running in the background. Click to view the specific instructions .Docker After the startup is successful, you can see the running status of the container in the application :Docker Containers

Browser access: localhost:8080To access adminerthe page, you first need to log in

Enter Mysql imagethe account information configured above, and you can see testdbthat there is notable

4.Create user table

In order to query and create the table in the following nestjslinks , create the table in advance, including the fields: sql is as follows:mysql userid,name,age

CREATE TABLE IF NOT EXISTS user (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL
);

The steps on adminerthe above:

Nestjs link mysql

Here we use the TypeORM framework (ORM object relational mapping) to establish a connection between the application and the database. It provides an efficient way to perform database operations. It is better to use @nestjs/typeormTypeORM

  1. Install TypeORM dependencies
npm install --save @nestjs/typeorm typeorm mysql2

2.CreateUser module
This article mainly introduces User tablethe operation, so here we use nest clithe quick creation of the module ( cli command to understand ), create in order:

nest g mo user 
nest g co user --no-spec
nest g s user --no-spec

After the command is executed, srca corresponding file will appear after the directory user. At this time, you also need to src/usercreate a user entity class in the directoryuser.entity.ts

// src/user/user.entity.ts

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

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

@Column()
name: string;

@Column()
age: number;
}

user.service.tsCreate a query in the file and add a user method

// src/user/user.service.ts

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

@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private usersRepository: Repository<User>,
) { }

findAll(): Promise<User[]> {
return this.usersRepository.find();
}

create(user: User): Promise<User> {
return this.usersRepository.save(user);
}
}

user.controller.tsAdd the corresponding API request interface:

  • Query user: GET localhost:3000/users
  • Create user: POSTlocalhost:3000/users
// src/user/user.controller.ts

import { Controller, Get, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';

@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) { }

@Get()
findAll(): Promise<User[]> {
return this.userService.findAll();
}

@Post()
create(@Body() user: User): Promise<User> {
return this.userService.create(user);
}

}

user.module.tsIntroducing typeorm and user.entity.tsentity class mapping mysql user

// src/user/user.module.ts

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

@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService],
controllers: [UserController],
})
export class UserModule { }

3. Configure mysql connect

In the project src/app.module.ts(root module) @nestjs/typeormlink it viamysql

// src/app.module.ts

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

@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3307,
username: 'root',
password: 'example',
database: 'testdb',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
UserModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule { }

Operate the user table

This article Postmanuses a convenient and fast interface request

  1. POST request localhost:3000/userscreates usera record, and the Body uses the Json format (NestJS provides strong support for the JSON format. By using @Body()decorators)

The interface successfully returns the added user record

2. GET request localhost:3000/users, view userlist

Finally, we can also adminerview user tablethe data inserted in

Summarize

This article mainly uses TypeORMthe nestjsapplication link mysqlto user tablecreate and query data. In order to smooth the differences in the operating environment during the development process, Dockerthe installationmysql and adminer

--

--

Neo Luo

I am a full stack developer, engaged in development for more than 10 years, developing e-commerce, tourism, finance, web3, ai, I will share more