Nest-连接数据库
NestJS 中,使用 TypeORM
或 Sequelize
库实现数据库连接。这里我选择的是 TypeORM
,与 NestJS 集成比较方便
安装依赖
这里我们采用的是mysql2 以及typeorm的结合,先安装一下对应的数据库依赖
javascript
yarn add @nestjs/typeorm typeorm mysql2
配置数据库
创建数据库nexusnest
,创建表users
javascript
CREATE TABLE `users` (
`username` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_bin NOT NULL,
`id` int(0) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_bin ROW_FORMAT = Dynamic;
接下来我们在根文件app.module.ts
配置TypeORM 以连接 MySQL 数据库
javascript
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserController } from './user/user.controller';
import { UserService } from './user/user.service';
import { User } from './user/user.entity';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql', // 可以选择其他数据库,如 MySQL
host: 'localhost',
port: 3306,
username: 'root',
password: 'xxxxxx',
database: 'nexusnest',
entities: [User],
synchronize: true,
}),
TypeOrmModule.forFeature([User]),
],
controllers: [UserController],
providers: [UserService],
})
export class AppModule {}
创建数据库实体User(user.entity.ts)
这里User最终我们操作从顶层到底层分别是数据库方法=> 数据库逻辑 => 数据库实体层
javascript
user.controller.ts=> user.service.ts => user.entity.ts
这里我们以User为主,先看看如何创建一个数据库表对应的实体,根文件下面新建一个用户实体user.entity.ts
文件
javascript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('users')
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
}
那么我们这里的User的实体就是:
javascript
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity('sys_user') // 映射到数据库中的 sys_user 表
export class User {
@PrimaryGeneratedColumn({ name: 'user_id' }) // 设置主键列
userId: number;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '姓名' })
name: string | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '年龄' })
age: string | null;
@Column({ nullable: true, type: 'int', comment: '用户性别 1男 2女' })
sex: number | null;
@Column({ nullable: true, type: 'datetime', comment: '创建时间' })
createTime: Date | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '用户的地址' })
address: string | null;
@Column({ nullable: true, type: 'tinyint', comment: '1 正常 0 2 禁用' })
state: number | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '手机号' })
phone: string | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '用户的登录账号' })
username: string | null;
@Column({ length: 255, charset: 'utf8mb3', default: '123456', comment: '用户的登录密码' })
password: string;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '头像地址' })
avatar: string | null;
@Column({ nullable: true, type: 'datetime', comment: '更新时间' })
updateTime: Date | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '身高' })
userHeight: string | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3', comment: '体重' })
userWeight: string | null;
@Column({ nullable: true, length: 255, charset: 'utf8mb3',
comment: '健康状况,是否有疾病' })
disease: string | null;
}
上面部分的name: string | null
应该改成name: string
javascript
string | null => string
原因:
我们使用的TS推断对应的数据类型为联合类型,但是数据库数据库列的定义可能
无法理解这个联合类型,特别是在 TypeScript 与数据库的映射过程中
出现的类型推断问题。
解决方法:
但是其实这里的 nullable: true在TypeORM映射过程之中已经代表了可以为空
这里我们去掉即可
创建用户数据库逻辑Service(user.service.ts)
使用 Repository 或 Service 操作数据,创建一个 UserService
来管理 User
实体的数据操作。
接下来我们使用 @InjectRepository()
注入 User
实体的 Repository,并在服务中进行数据查询或增删改查操作。
创建 user.service.ts
:
javascript
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 userRepository: Repository<User>,
) {}
// 获取所有用户
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
}
创建用户控制方法(user.controller.ts)
创建控制器来处理请求和返回响应
javascript
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()
async findAll(): Promise<User[]> {
return this.userService.findAll();
}
// 创建一个新的用户
@Post()
async create(
@Body('firstName') firstName: string,
@Body('lastName') lastName: string,
@Body('age') age: number,
): Promise<User> {
return this.userService.createUser(firstName, lastName, age);
}
}
访问测试
创建完成以后重新启动
javascript
yarn run start
访问下面的地址
http://localhost:3000/users
这个时候我们已经可以得到下面的数据了
javascript
[{"id":1,"username":"12"}]
这里就代表我们数据库已经链接成功了