Skip to main content

将 Prisma Postgres 与 TypeORM 结合使用

TypeORM 是一个 TypeScript ORM。在本指南中,你将学习如何将 TypeORM 连接到 Prisma Postgres

¥TypeORM is a TypeScript ORM. In this guide, you'll learn how to connect TypeORM to Prisma Postgres.

先决条件

¥Prerequisites

  • Node.js 版本 16 或更高版本

    ¥Node.js version 16 or higher

  • TypeScript 版本 4.5 或更高版本

    ¥TypeScript version 4.5 or higher

1. 生成一个 TypeORM 项目

¥ Generate a TypeORM project

使用 TypeORM CLI 生成初始项目:

¥Use the TypeORM CLI to generate a starter project:

npx typeorm init --name typeorm-quickstart --database postgres

此命令将生成一个具有以下结构的新项目:

¥This command will generate a new project with the following structure:

typeorm-quickstart
├── src
│ ├── entity
│ │ └── User.ts # Sample entity
│ ├── migration # Migrations folder
│ ├── data-source.ts # Data source configuration
│ └── index.ts # Application entry point
├── .gitignore
├── package.json
├── README.md
└── tsconfig.json

2. 安装依赖

¥ Install dependencies

进入项目目录并安装依赖:

¥Navigate to the project directory and install dependencies:

cd typeorm-quickstart
npm install

安装 dotenv 以加载环境变量:

¥Install dotenv to load environment variables:

npm install dotenv

3. 创建 Prisma Postgres 数据库

¥ Create a Prisma Postgres database

你可以使用 create-db CLI 工具创建 Prisma Postgres 数据库。按照以下步骤创建你的 Prisma Postgres 数据库:

¥You can create a Prisma Postgres database using the create-db CLI tool. Follow these steps to create your Prisma Postgres database:

npx create-db

然后 CLI 工具应输出:

¥Then the CLI tool should output:

┌  🚀 Creating a Prisma Postgres database

│ Provisioning a temporary database in us-east-1...

│ It will be automatically deleted in 24 hours, but you can claim it.

◇ Database created successfully!


● Database Connection


│ Connection String:

│ postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require


◆ Claim Your Database

│ Keep your database for free:

│ https://create-db.prisma.io/claim?CLAIM_CODE

│ Database will be deleted on 11/18/2025, 1:55:39 AM if not claimed.


创建 .env 文件,并添加输出中的连接字符串:

¥Create a .env file and add the connection string from the output:

.env
DATABASE_URL="postgresql://hostname:password@db.prisma.io:5432/postgres?sslmode=require"
警告

切勿将 .env 文件提交到版本控制系统。将 .env 添加到 .gitignore 文件以确保凭据安全。

¥Never commit .env files to version control. Add .env to your .gitignore file to keep credentials secure.

创建的数据库是临时的,除非被认领,否则将在 24 小时后删除。认领操作会将数据库移动到你的 账户。访问输出中的声明 URL 以保留你的数据库。

¥The database created is temporary and will be deleted in 24 hours unless claimed. Claiming moves the database into your account. Visit the claim URL from the output to keep your database.

注意

要了解有关 create-db CLI 工具的更多信息,请参阅 create-db 文档

¥To learn more about the create-db CLI tool, see the create-db documentation.

4. 配置数据库连接

¥ Configure database connection

更新 src/data-source.ts 文件,使其使用你的 Prisma Postgres 连接:

¥Update the src/data-source.ts file to use your Prisma Postgres connection:

src/data-source.ts
import "reflect-metadata"
import "dotenv/config";
import { DataSource } from "typeorm"
import { User } from "./entity/User"

// Parse DATABASE_URL into connection parameters
function parseConnectionString(url: string) {
const parsed = new URL(url)
return {
host: parsed.hostname,
port: parseInt(parsed.port),
username: parsed.username,
password: parsed.password,
database: parsed.pathname.slice(1), // Remove leading '/'
}
}

const connectionParams = parseConnectionString(process.env.DATABASE_URL!)

export const AppDataSource = new DataSource({
type: "postgres",
host: "localhost",
port: 5432,
username: "test",
password: "test",
database: "test",
...connectionParams,
ssl: true,
synchronize: true,
logging: false,
entities: [User],
migrations: [],
subscribers: [],
})

5. 运行应用

¥ Run the application

启动应用:

¥Start the application:

npm start

你应该看到指示连接成功且已将新用户插入数据库的输出:

¥You should see output indicating the connection was successful and a new user was inserted into the database:

Inserting a new user into the database...
Saved a new user with id: 1
Loading users from the database...
Loaded users: [ User { id: 1, firstName: 'Timber', lastName: 'Saw', age: 25 } ]

下一步

¥Next steps

你已成功将 TypeORM 连接到 Prisma Postgres!对于实体、迁移和查询等更高级的功能,请参阅 TypeORM 文档

¥You've successfully connected TypeORM to Prisma Postgres! For more advanced features like entities, migrations, and queries, see the TypeORM documentation.