Nest.js - 连接数据库

Mysql

以下以连接Mysql数据为例子,技术选型为NestJS + Mysql + TypeOrm

安装

安装依赖

sql 复制代码
pnpm add @nestjs/typeorm typeorm mysql2

导入TypeOrmModule

php 复制代码
// app.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TestModule } from './module/test/test.module';
​
@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: 'root123', // 替换为你自己的密码
      database: 'test_egg', // 替换为你创建的数据库名
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true, // 开发环境可开启,生产环境务必关闭!
      retryDelay: 500,
      retryAttempts: 10,
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {}

参数介绍:

arduino 复制代码
// 指定实体文件路径,`TypeORM `会自动加载这些类作为数据模型
entities
// 仅限开发环境!它会根据实体自动创建/修改表结构,非常方便
// 但上线后必须设为false,否则可能误删表;
synchronize: true:
// 网络抖动时重试策略,避免启动失败
retryDelay 和 retryAttempts

创建实体与服务

新建src/module/test/test.entity.ts

kotlin 复制代码
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
​
@Entity()
export class Test {
  @PrimaryGeneratedColumn()
  id: number;
​
  @Column()
  name: string;
}

test.module.ts中引入实体

typescript 复制代码
import { Module } from '@nestjs/common';
// 引入
import { TypeOrmModule } from '@nestjs/typeorm';
import { TestController } from './test.controller';
import { TestService } from './test.service';
// 引入实体
import { TestEntity } from './test.entity';
​
@Module({
  // 引入
  imports: [TypeOrmModule.forFeature([TestEntity])],
  controllers: [TestController],
  providers: [TestService],
})
export class TestModule {}

test.service.ts简单应用

typescript 复制代码
import { Injectable } from '@nestjs/common';
// 引入
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
// 引入
import { TestEntity } from './test.entity';
​
@Injectable()
export class TestService {
  constructor(
    // 注入
    @InjectRepository(TestEntity)
    private readonly testRepository: Repository<TestEntity>,
  ) {}
​
  async getHello(): Promise<string> {
    // 使用
    return this.testRepository
            .find()
            .then((res) => res.map((item) => item.name).join(','));
  }
}
相关推荐
windliang22 分钟前
Claude Code 源码分析(十二):错误处理与自动恢复:让 Agent 稳定运行
前端·javascript·面试
默_笙31 分钟前
🛬 前端路由的"高级玩法":懒加载、404、鉴权路由,一个都不能少(下篇)
前端·javascript
sunly_31 分钟前
TypeScript:3、类型声明与类型推断
javascript·ubuntu·typescript
奥莱维2 小时前
【无标题】
java·前端·javascript
黄金决明子3 小时前
浏览器Window底层操作全解
前端·javascript
AI视觉网奇4 小时前
cannot import name ‘model_urls‘ from ‘torchvision.models.resnet‘
linux·前端·javascript
Sca_杰4 小时前
微信客服API对接速通
javascript·node.js
大家的林语冰5 小时前
👍 JS 还在进化,ES2026 正式推出,最新七大特性补全!
前端·javascript·json
铁皮饭盒5 小时前
DeepSeek V4 Pro 0813发布了, 也可以部署到 Codex 了
前端·javascript·后端
Highcharts.js5 小时前
Vue 3 + Highcharts Boost 可视化加速模块的完整示例
javascript·vue.js·可视化·boost·highcharts·图表渲染·加速模块