Outline: Add Prisma ORM to a Node.js project using PostgreSQL DB

Outline: Add Prisma ORM to a Node.js project using PostgreSQL DB

大纲:在 Node.js 项目中使用 PostgreSQL 数据库添加 Prisma ORM

Quick outline to add Prisma ORM to any Node.js or Express project using a PostgreSQL DB. This outline will work if adding Prisma to an existing or new Node.js project. 这是一个为任何使用 PostgreSQL 数据库的 Node.js 或 Express 项目添加 Prisma ORM 的快速大纲。无论你是为现有项目还是新项目添加 Prisma,此大纲均适用。

Install required packages and dependencies

安装所需的包和依赖项

Navigate to your project directory or create the project directory and install these required dependencies using any package manager you like: 进入你的项目目录(或创建一个新目录),并使用你喜欢的包管理器安装以下必要的依赖项:

npm install prisma@prev @types/node @types/pg --save-dev
npm install @prisma/client@7 @prisma/adapter-pg pg dotenv

The prisma package is a CLI tool that enables us run commands on the terminal like prisma init, migrate, pull and studio. @prisma/client is the client library querying the database, @prisma/adapter-pg, pg & @types/pg are the node_postgres driver adapter, driver and TypeScript type definitions that connect Prisma to client Postgres database. prisma 包是一个命令行工具,使我们能够在终端运行诸如 prisma init、migrate、pull 和 studio 等命令。@prisma/client 是用于查询数据库的客户端库;而 @prisma/adapter-pg、pg 和 @types/pg 则是 node_postgres 驱动适配器、驱动程序以及 TypeScript 类型定义,它们负责将 Prisma 连接到 PostgreSQL 数据库。

Initialize Prisma

初始化 Prisma

npx prisma init --datasource-provider postgresql --output ../generated/prisma

This command creates a prisma folder with a schema.prisma file in it; the file contains your db connection setup in it. And also a .env and prisma configuration file prisma7.config.ts are created in the root directory. 此命令会创建一个包含 schema.prisma 文件的 prisma 文件夹;该文件包含了你的数据库连接设置。此外,根目录下还会创建 .env 文件和 Prisma 配置文件 prisma7.config.ts。

Connect your database

连接你的数据库

DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"

Edit the connection to match your database details. 请编辑连接字符串以匹配你的数据库详细信息。

Next step

下一步

Either pull your existing database using this command: 你可以使用以下命令拉取现有的数据库结构:

npx prisma db pull

Or update the prisma/schema.prisma file: 或者手动更新 prisma/schema.prisma 文件:

generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model User {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}
## your other tables
## 你的其他表

Migrate and push your new database schema: 迁移并推送你的新数据库架构:

npx prisma migrate dev --name init