跳到主要内容

配置 postgres 数据库

使用 docker 模拟

创建 ./docker-compose.yml 文件

version: '3.8'
services:
  dev-db:
    image: postgres:14
    ports:
      - 5434:5432
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: 123
      POSTGRES_DB: nest
    networks:
      - freecodecamp
networks:
  freecodecamp:
docker compose up dev-db -d

使用 ORM 管理数据

prisma

推荐使用 prisma ,目前 star 数已经遥遥领先。

pnpm i -D prisma@latest
pnpm i @prisma/client

初始化数据

npx prisma init

# prisma
# └── schema.prisma

创建 prisma model

prisma/schema.prisma

model User {
  id       Int      @id @default(autoincrement())
  createAt DateTime @default(now())
  updateAt DateTime @updatedAt

  email String
  hash  String

  firstName String?
  lastName  String?
}

model Bookmark {
  id       Int      @id @default(autoincrement())
  createAt DateTime @default(now())
  updateAt DateTime @updatedAt

  title       String
  link        String
  description String?
}

配置 env

DATABASE_URL="postgresql://postgres:123@localhost:5434/nest?schema=public"
# DATABASE_URL="postgresql://<username>:<password>@localhost:<port>/<database_name>?schema=public"

prisma cli

Usage

$ prisma [command]

Commands

init Set up Prisma for your app
generate Generate artifacts (e.g. Prisma Client)
db Manage your database schema and lifecycle
migrate Migrate your database
studio Browse your data with Prisma Studio
validate Validate your Prisma schema
format Format your Prisma schema
version Displays Prisma version info
debug Displays Prisma debug info

Flags

--preview-feature Run Preview Prisma commands
--help, -h Show additional information about a command

Examples

Set up a new Prisma project
$ prisma init

Generate artifacts (e.g. Prisma Client)
$ prisma generate

Browse your data
$ prisma studio

Create migrations from your Prisma schema, apply them to the database, generate artifacts (e.g. Prisma Client)
$ prisma migrate dev

Pull the schema from an existing database, updating the Prisma schema
$ prisma db pull

Push the Prisma schema state to the database
$ prisma db push

Validate your Prisma schema
$ prisma validate

Format your Prisma schema
$ prisma format

Display Prisma version info
$ prisma version

Display Prisma debug info
$ prisma debug
npx prisma migrate dev

使用 studio 查看数据库数据

npx prisma studio
# http://localhost:5555

创建 prisma 管理 nest model

nest g module prisma
nest g service prisma --no-spec
src/prisma
├── prisma.module.ts
└── prisma.service.ts