0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Nest.js】TypeORMを使ってPostgreSQLと接続する

Last updated at Posted at 2025-11-23

Blue, Orange and Grey Illustrated Ethical Hacking Toutube Thumbnail  .png

ディレクトリ情報

image.png

技術のバージョン情報

 技術   バージョン 
 NestJS   11.0.1 
 TypeORM   0.3.27 

1.モジュールのインストール

このセクションでは、TypeORMとPostgreSQLのモジュールをそれぞれインストールしていきます。

まずは、TypeORMモジュールのインストールです。

nestjs/typeormのインストール

npm i --save @nestjs/typeorm typeorm

つづいて、PostgreSQLモジュールのインストールです。

PostgreSQLドライバpgのインストール

npm install pg

2.DB設定ファイルの新規作成

このセクションでは、PostgreSQLのデータベース情報を作成していきます。
プロジェクトルート直下にormconfig.jsonという名前のファイルを作成します。
作成したormconfig.jsonに下記のように記載していきましょう。

ormconfig.json
{
    "type":"postgres",
    "host":"localhost",
    "port":"5432",
    "username":"ユーザ名",
    "password":"パスワード",
    "database":"データベース名",
    "entities":["dist/**/*.entity{.ts,.js}"],
    "synchronize":true
}

3.DB情報をapp.module.tsにインポート

このセクションでは、前掲「2.DB設定ファイルの新規作成」で作成したormconfig.jsonsrc/app.module.tsに読み込ませる方法です。

手順

1.TypeOrmModuleをインポートします。

src/app.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';

2.DB設定情報ormconfig.jsonをインポートします。

src/app.module.ts
import * as config from "ormconfig.json"

3.TypeOrmModuleのforRoot関数を使ってDB設定情報ormconfig.jsonを読み込む。

src/app.module.ts
//(略)
@Module({
  imports: [
    TypeOrmModule.forRoot(config as any),//追加
  ],
//(略)

全体のコードはこちら⇩

src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HelloController } from './hello/hello.controller';
import { TypeOrmModule } from '@nestjs/typeorm';//追加
import * as config from "ormconfig.json"//設定ファイルの読み込み

@Module({
  imports: [
    TypeOrmModule.forRoot(config as any),//追加
  ],
  controllers: [AppController, HelloController],
  providers: [AppService],
})
export class AppModule {}

4. アプリを起動

最後に、下記のコマンドでアプリを起動しましょう。

npm run start:dev

下記のようにコンソールに表示出来たら完了です。
image.png

サイト

Devicon:アイコンサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?