1.安装typeorm
npm install --save @nestjs/typeorm typeorm mysql2
2.vscode安装可视化工具 Database Client
3.连接数据库
4.nest连接数据库表
import { TypeOrmModule } from '@nestjs/typeorm';
import { TestModule } from './test/test.module';
imports: [
TypeOrmModule.forRoot({
type: 'mysql', //数据库类型
username: 'root', //账号
password: '123456', //密码
host: 'localhost', //host
port: 3306, //
database: 'db', //库名
// entities: [__dirname + '/**/*.entity{.ts,.js}'], //实体文件
synchronize: true, //synchronize字段代表是否自动将实体类同步到数据库
retryDelay: 500, //重试连接数据库间隔
retryAttempts: 10, //重试连接数据库的次数
autoLoadEntities: true, //如果为true,将自动加载实体 forFeature()方法注册的每个实体都将自动添加到配置对象的实体数组中
}),
TestModule,
],
5.创建test类 nest g res test
// 定义一个实体类
import {
Entity,
Column,
PrimaryGeneratedColumn,
CreateDateColumn,
Generated,
} from 'typeorm';
@Entity()
export class Test {
// 自增id
@PrimaryGeneratedColumn()
id: number;
// 自动生成列
@Generated('uuid')
uuid: string;
@Column()
name: string;
// 不返回密码给用户,注释,可以为空,默认值123
@Column({ select: true, comment: '注释', nullable: true, default: '123' })
password: string;
@Column()
age: number;
//时间戳
@CreateDateColumn({ type: 'timestamp' })
createTime: Date;
// 枚举列
@Column({
type: 'enum',
enum: ['1', '2', '3', '4'],
default: '1',
})
xx: string;
// simple-array的特殊列类型,它可以将原始数组值存储在单个字符串列中
@Column('simple-array')
names: string[];
// simple-json的特殊列类型,它可以存储任何可以通过 JSON.stringify 存储在数据库中的值
@Column('simple-json')
profile: { name: string; nickname: string };
}
6.导出实体类
import { Test } from './entities/test.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
imports: [TypeOrmModule.forFeature([Test])],
7.运行项目看看数据库有没有生成test表