如何从 Mongoose 迁移到 Prisma ORM
简介
本指南将向您展示如何将应用程序从 Mongoose 迁移到 Prisma ORM。我们将使用 Mongoose Express 示例 的扩展版本作为 示例项目,以演示迁移步骤。
您可以在“Prisma ORM 对比 Mongoose”页面上了解 Prisma ORM 与 Mongoose 的对比。
先决条件
在开始本指南之前,请确保您具备以下条件:
- 您想要迁移的 Mongoose 项目
- 已安装 Node.js (版本 18 或更高)
- MongoDB 数据库
- 对 Mongoose 和 Express.js 有基本了解
1. 准备迁移
1.1. 了解迁移过程
无论您正在构建何种应用程序或 API 层,从 Mongoose 迁移到 Prisma ORM 的步骤始终相同:
- 安装 Prisma CLI
- 内省您的数据库
- 安装并生成 Prisma Client
- 逐步将 Mongoose 查询替换为 Prisma Client
这些步骤适用于您正在构建 REST API (例如,使用 Express、Koa 或 NestJS)、GraphQL API (例如,使用 Apollo Server、TypeGraphQL 或 Nexus) 或任何其他使用 Mongoose 进行数据库访问的应用程序。
1.2. 设置 Prisma 配置
创建新的 Prisma schema 文件
npx prisma init --datasource-provider mongodb --output ../generated/prisma
此命令将创建
- 一个名为
prisma
的新目录,其中包含一个schema.prisma
文件;您的 Prisma schema 指定了您的数据库连接和模型 .env
:项目根目录下的一个dotenv
文件(如果尚不存在),用于将数据库连接 URL 配置为环境变量
Prisma schema 目前如下所示
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
为了在使用 Prisma ORM 时获得最佳开发体验,请参阅编辑器设置,了解语法高亮、格式化、自动完成以及更多很酷的功能。
使用您的 MongoDB 连接字符串更新 .env
文件中的 DATABASE_URL
DATABASE_URL="mongodb://USER:PASSWORD@HOST:PORT/DATABASE"
2. 迁移数据库 schema
2.1. 内省您的数据库
MongoDB 是一个无模式数据库。要在项目中逐步采用 Prisma ORM,请确保您的数据库已填充示例数据。Prisma ORM 通过采样存储的数据并从数据库中的数据推断 schema 来内省 MongoDB schema。
运行 Prisma 的内省功能,从您现有的数据库中创建 Prisma schema
npx prisma db pull
这将创建一个包含您的数据库 schema 的 schema.prisma
文件。
type UsersProfile {
bio String
}
model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
}
model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
author String @db.ObjectId
categories String[] @db.ObjectId
content String
published Boolean
title String
}
model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
}
2.2. 更新关系
MongoDB 不支持不同集合之间的关系。但是,您可以使用 ObjectId
字段类型在文档之间创建引用,或者在集合中使用 ObjectIds
数组从一个文档引用多个文档。引用将存储相关文档的 ID。您可以使用 Mongoose 提供的 populate()
方法来用相关文档的数据填充引用。
如下更新 posts
<-> users
之间的一对多关系
- 将
posts
模型中现有的author
引用重命名为authorId
并添加@map("author")
属性 - 在
posts
模型中添加author
关系字段及其@relation
属性,指定fields
和references
- 在
users
模型中添加posts
关系
您的 schema 现在应该如下所示
type UsersProfile {
bio String
}
model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
}
model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
published Boolean
v Int @map("__v")
author String @db.ObjectId
author users @relation(fields: [authorId], references: [id])
authorId String @map("author") @db.ObjectId
categories String[] @db.ObjectId
}
model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
posts posts[]
}
然后,如下更新 posts
<-> categories
之间的多对多引用
- 在
posts
模型中将categories
字段重命名为categoryIds
并使用@map("categories")
进行映射 - 在
posts
模型中添加一个新的categories
关系字段 - 在
categories
模型中添加postIds
标量列表字段 - 在
categories
模型中添加posts
关系 - 在两个模型上添加一个关系标量
- 在两侧添加
@relation
属性,指定fields
和references
参数
您的 schema 现在应该如下所示
type UsersProfile {
bio String
}
model categories {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
name String
posts posts[] @relation(fields: [postIds], references: [id])
postIds String[] @db.ObjectId
}
model posts {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
content String
published Boolean
v Int @map("__v")
author users @relation(fields: [authorId], references: [id])
authorId String @map("author") @db.ObjectId
categories String[] @db.ObjectId
categories categories[] @relation(fields: [categoryIds], references: [id])
categoryIds String[] @map("categories") @db.ObjectId
}
model users {
id String @id @default(auto()) @map("_id") @db.ObjectId
v Int @map("__v")
email String @unique(map: "email_1")
name String
profile UsersProfile?
posts posts[]
}
3. 更新您的应用程序代码
3.1. 安装 Prisma Client
安装 Prisma Client 包
npm install @prisma/client
安装 Prisma Client 包后,生成 Prisma Client
npx prisma generate
3.2. 替换 Mongoose 查询
开始使用 Prisma Client 替换您的 Mongoose 查询。以下是转换一些常见查询的示例:
- Mongoose
- Prisma Client
// Find one
const user = await User.findById(id);
// Create
const user = await User.create({
email: 'alice@prisma.io',
name: 'Alice'
});
// Update
await User.findByIdAndUpdate(id, {
name: 'New name'
});
// Delete
await User.findByIdAndDelete(id);
// Find one
const user = await prisma.user.findUnique({
where: { id }
});
// Create
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice'
}
});
// Update
await prisma.user.update({
where: { id },
data: { name: 'New name' }
});
// Delete
await prisma.user.delete({
where: { id }
});
3.3. 更新您的控制器
更新您的 Express 控制器以使用 Prisma Client。例如,以下是如何更新用户控制器:
import { prisma } from '../client'
export class UserController {
async create(req: Request, res: Response) {
const { email, name } = req.body
const result = await prisma.user.create({
data: {
email,
name,
},
})
return res.json(result)
}
}
下一步
现在您已迁移到 Prisma ORM,您可以:
- 使用 Prisma 强大的查询 API 添加更复杂的查询
- 设置 Prisma Studio 进行数据库管理
- 实现数据库监控
- 使用 Prisma 的测试实用程序添加自动化测试
更多信息
与 Prisma 保持联系
通过以下方式继续您的 Prisma 之旅: 我们活跃的社区。保持信息畅通,积极参与,并与其他开发者协作
- 在 X 上关注我们 获取公告、直播活动和实用技巧。
- 加入我们的 Discord 提问,与社区交流,并通过对话获得积极支持。
- 在 YouTube 上订阅 获取教程、演示和直播。
- 在 GitHub 上参与 通过给仓库加星、报告问题或贡献问题来参与。