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 nestjs
through 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 Postman
viewing the applicationnestjs mysql
Quickly create a nestjs application
Quickly create an application through nestjs CLI
scaffolding ( 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
- First you need to download
Docker
the application
Download the installation package for the corresponding system
Docker
After successful installation, click on the app and you can see Containers
that it is empty.
2. createdocker-compose.yml
Create a configuration file for the container application in the project mysql-nestjs
root 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:
mysql
The default imageusername
isroot
, password isexample
, and database is:testdb
adminer
A simple and powerful tool for managing databases, convenient for visualizing data, bylocalhost:8080
accessing the page
3. Start Docker
the container
Run the command to start in the project mysql-nestjs
root directoryDocker image
docker-compose up -d
-d
The 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:8080
To access adminer
the page, you first need to log in
Enter Mysql image
the account information configured above, and you can see testdb
that there is notable
4.Create user table
In order to query and create the table in the following nestjs
links , 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 adminer
the 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
- Install TypeORM dependencies
npm install --save @nestjs/typeorm typeorm mysql2
2.CreateUser module
This article mainly introduces User table
the operation, so here we use nest cli
the 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, src
a corresponding file will appear after the directory user
. At this time, you also need to src/user
create 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.ts
Create 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.ts
Add the corresponding API request interface:
- Query user: GET
localhost:3000/users
- Create user: POST
localhost: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.ts
Introducing typeorm and user.entity.ts
entity 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/typeorm
link 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 Postman
uses a convenient and fast interface request
- POST request
localhost:3000/users
createsuser
a 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 user
list
Finally, we can also adminer
view user table
the data inserted in
Summarize
This article mainly uses TypeORM
the nestjs
application link mysql
to user table
create and query data. In order to smooth the differences in the operating environment during the development process, Docker
the installationmysql and adminer