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(','));
  }
}
相关推荐
2601_962097481 小时前
JavaScript 异步编程
javascript·ajax·回调函数·异步编程·子线程
张洪权1 小时前
nest.js websocket 群聊----私聊功能
前端·nestjs
全栈项目管理程序猿1 小时前
ArcGIS JS 基础教程(18):SceneLayer 场景图层
javascript
leoZ2311 小时前
第 2 篇:搭建地基——Vue3 + Vite + Tailwind v4 + shadcn-vue
前端·javascript·vue.js·人工智能·目标检测·数据挖掘·语音识别
七牛开发者2 小时前
拆解 dsh:Session 的事件溯源与状态重建
javascript·github·agent
梨想橙汁2 小时前
JS BOM 浏览器对象:定时器与同步异步底层理解
前端·javascript
梨想橙汁2 小时前
ES6+ 必用新特性:箭头函数、解构、模板字符串、扩展运算符
前端·javascript
梨想橙汁2 小时前
DOM 与 JS 事件:页面元素操作、事件冒泡、事件委托实战
前端·javascript
一个游离的指针2 小时前
浏览器的渲染原理
前端·javascript
ynchyong3 小时前
JavaScript Promise 实战:.then() 与 .catch() 的区别及回调函数封装指南
开发语言·javascript·ecmascript·promise·then