iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 14
0
Modern Web

讀官網文件邊走邊學nest.js系列 第 14

Day14-TypeORM(一)-連線設定

  • 分享至 

  • twitterImage
  •  

nest.js團隊選用TypeORM作為與資料庫互動的介面,TypeORM也是以Typescript開源專案

nest.js裡使用TypeORM先要安裝下列套件

yarn add @nestjs/typeorm typeorm

再來根據選用的資料庫,到TypeORM Github,額外安裝套件
例如選用PostgreSQL

yarn add pg

TypeORM也提供CLI

npm install typeorm -g

專案目錄下輸入

typeorm init --database postgres

會展生ormconfig.json

{
   "type": "postgres",
   "host": "localhost",
   "port": 5432,
   "username": "postgres", //輸入預設的root帳號
   "password": "xxx", // 密碼
   "database": "users", // 指定資料庫名稱
   "synchronize": true,
   "logging": false,
   "entities": [ // mapping class的放的位置,指定放在shared下
      "src/shared/entity/**/*.ts"
   ],
   "migrations": [ // 存放資料庫版本管控(migration)的檔案,指定放在shared下
      "src/shared/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": { //預設使用CLI產生檔案的目錄,指定放在shared資料夾下
      "entitiesDir": "src/shared/entity",
      "migrationsDir": "src/shared/migration",
      "subscribersDir": "src/shared/subscriber"
   }
}

利用CLI建立第一個Entity Class

typrorm entity:create -n User

import {Entity, PrimaryGeneratedColum} from "typeorm";

@Entity()
export class User {
    @PrimaryGeneratedColumn() //建立table需要primary key
    id: number;
}

在app.module.ts import TypeOrmModule

app.module.ts

...
mport {TypeOrmModule} from '@nestjs/typeorm';

@Module({
  imports: [
    SharedModule,
    TypeOrmModule.forRoot(),
  ],
...

開啟pgadmin4新增users database
yarn start:dev

user table已建立


上一篇
Day13- Interceptor in nest.js
下一篇
Day15-TypeORM(二)-新增資料
系列文
讀官網文件邊走邊學nest.js31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言