Skip to main content

从 MongoDB Beta 升级

介绍

¥Introduction

本指南帮助你从 Prisma 1 MongoDB Beta 迁移到 Prisma ORM 2 或更高版本上的 MongoDB。要了解有关 Prisma 1 和 Prisma ORM 2.x 及更高版本之间的差异的更多信息,请参阅 这个文件

¥This guide helps you migrate from the Prisma 1 MongoDB Beta to MongoDB on Prisma ORM 2 or later. To learn more about the differences between Prisma 1 and Prisma ORM 2.x and later, refer to this document.

本指南的目的是为你提供执行迁移所需的工作流程并重点介绍你可能遇到的一些问题。

¥The scope of this guide is to give you the workflow necessary to perform the migration and highlight some of the problems you might encounter.

遗憾的是,我们无法涵盖所有可能的情况或所需的更改,但本指南应该对你的旅程有所帮助。如果有任何问题,请加入 我们的 Discord 或创建问题 在 Github 上

¥We unfortunately can't cover all possible scenarios or changes required, but this guide should help you on your journey. Join our Discord or create an issue on Github with any questions.

warning

在生产中尝试此操作之前,请在临时环境中执行此迁移!

¥Perform this migration on your staging environment before trying this in production!

要求

¥Requirements

  • 必须将 MongoDB 4.2+ 作为副本集运行(MongoDB Atlas 自动为你执行此操作)

    ¥Must be running MongoDB 4.2+ as a replica set (MongoDB Atlas does this for you automatically)

  • 节点.js:参见 系统要求

    ¥Node.js: see system requirements

  • TypeScript:参见 系统要求

    ¥TypeScript: see system requirements

安装 Prisma ORM 3.12.0 或更高版本

¥Installing Prisma ORM 3.12.0 or later

在你的项目目录中运行以下命令:

¥In your project directory run the following commands:

npm install prisma@latest && npm install @prisma/client
npx prisma init --datasource-provider=mongodb

这应该创建以下文件:

¥This should create the following files:

  • prisma/schema.prisma:初始 Prisma 架构

    ¥prisma/schema.prisma: An initial Prisma schema

  • .env:你将在其中存储连接字符串的环境文件

    ¥.env: Environment file where you'll store your connection string

info

如果你看到以下错误:

¥If you see the following error:

ERROR  File schema.prisma already exists in your project.
Please try again in a project that is not yet using Prisma.

你的项目中可能已经有 prisma/ 目录。将该目录重命名为 _prisma/ 之类的名称,然后重试

¥You have likely a prisma/ directory in your project already. Rename that directory to something like _prisma/ and try again

找到 MongoDB 数据库的连接字符串

¥Find the Connection String to your MongoDB Database

接下来,你需要找到 MongoDB 数据库的连接字符串。你应该能够在 docker-compose.yml 文件或 MongoDB Atlas 上找到它。这就是你要传递给 MongoDB Compass 的内容。连接字符串应如下所示:

¥Next you'll want to find the connection string to your MongoDB database. You should be able to find it in your docker-compose.yml file or on MongoDB Atlas. It's what you'd pass to MongoDB Compass. The connection string should look something like this:

mongodb://<user>:<pass>@<host>:27017

Prisma 1 中存储应用数据的数据库称为 default_default,因此我们将其添加到连接字符串的末尾,并更新 .env 文件中的 DATABASE_URL

¥The database that stores application data in Prisma 1 is called default_default, so we'll add that to the end of the connection string and update the DATABASE_URL key in the .env file

.env
DATABASE_URL="mongodb://prisma:prisma@localhost:27017/default_default"

内省你的 MongoDB 数据库

¥Introspect your MongoDB Database

你现在已准备好将数据库结构拉入 Prisma 架构中。

¥You're now ready to pull the structure of your database down into your Prisma Schema.

$ npx prisma db pull

你应该会看到 prisma/schema.prisma 中的 Prisma 架构已填充有你的模型。

¥And you should see your Prisma schema in prisma/schema.prisma populated with your models.

info

如果你看到以下错误:Error in connector: SCRAM failure: Authentication failed.,请尝试将 ?authSource=admin 添加到连接字符串的末尾,然后重试。

¥If you see the following error: Error in connector: SCRAM failure: Authentication failed., try adding ?authSource=admin to the end of your connection string and trying again.

修改你的 Prisma 架构

¥Touching up your Prisma Schema

从新反思的基于 Prisma 1 的 MongoDB 数据库生成的 Prisma 客户端可能没有最好的 API。你可以调整模型名称和字段,只需确保将 @map@@map 原始名称更改为底层数据库集合和字段名称:

¥The generated Prisma Client from a freshly introspected Prisma 1 based MongoDB database may not have the best API. You can adjust the model names and fields, just be sure to @map and @@map the original name to the underlying database collection and field names:

- model posts {
+ model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
published Boolean
title String
+ @@map("posts")
}

- model users {
+ model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique(map: "email_U")
name String
- posts String[] @db.ObjectId
+ postIds String[] @db.ObjectId @map("posts")

@@index([posts], map: "posts_R")
+ @@map("users")
}

进行这些重命名时要小心,因为你需要确保 Prisma 架构仍然正确映射到底层数据库集合和字段名称。

¥Take caution in doing these renames because you need to make sure the Prisma Schema still maps properly to the underlying database collections and field names.

与 SQL 数据库不同,MongoDB 对数据之间的关系没有明确的理解。这意味着 Prisma ORM 的内省无法为你推断这些关系。

¥Unlike SQL databases, MongoDB doesn't have an explicit understanding of relationships between data. This means that Prisma ORM's introspection is unable to infer those relationships for you.

我们通常建议在 本文档 的帮助下手动添加关系。但是,Prisma 1 存储外键的位置与 Prisma ORM 2 和更高版本期望外键的位置不同,因此如果你想利用关系,则需要在添加关系之前移动外键在数据库上的位置。

¥We typically recommend adding the relationships by hand with the help of this documentation. However, Prisma 1 stores foreign keys is different than where Prisma ORM 2 and later expects foreign keys, so if you want to take advantage of relationships, you'll need to shift where the foreign keys are on your database before adding the relationships.

tip

💡 下载 Prisma VSCode 扩展,在你转换 Prisma 架构时提供自动补齐和有用的错误消息。

¥💡 Download the Prisma VSCode Extension to provide autocomplete and helpful error messages as you transition your Prisma schema.

生成 Prisma 客户端

¥Generating a Prisma Client

使用数据架构填充 Prisma 架构后,你现在可以生成 Typescript 客户端来读取和写入 MongoDB 数据库。

¥With the Prisma schema populated with the schema of your data, you're now ready to generate a Typescript Client to read and write to your MongoDB database.

$ npx prisma generate

测试读取

¥Testing Reads

创建一个简单的 test.ts 脚本来验证 Prisma 客户端可以读取和写入你的应用。请注意,本指南使用的是 Prisma 1 示例存储库 中的示例,但代码会根据你的应用而变化。

¥Create a simple test.ts script to verify that Prisma Client can read and write to your application. Note that this guide is using the example in the Prisma 1 examples repository, but the code will change depending on your application.

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

async function main() {
await prisma.$connect()
const posts = await prisma.post.findMany()
console.log(posts)
}

main()
.catch(console.error)
.finally(() => prisma.$disconnect())

确保 ts-node 已全局安装并运行:

¥Make sure ts-node is installed globally and run:

ts-node test.ts

你应该看到数据列表:

¥You should see a list of your data:

[
{
comments: [],
id: '62435a83fca136000996ba16',
content: 'https://www.prisma.io/day/',
published: true,
title: 'Join us for Prisma Day 2019 in Berlin',
wasCreated: 2022-03-29T19:14:11.172Z,
wasUpdated: 2022-03-29T19:14:11.172Z
},
{
comments: [ [Object] ],
id: '62435a83fca136000996ba18',
content: 'https://graphqlweekly.com/',
published: true,
title: 'Subscribe to GraphQL Weekly for community news',
wasCreated: 2022-03-29T19:14:11.369Z,
wasUpdated: 2022-03-29T19:14:11.369Z
},
{
comments: [],
id: '62435a83fca136000996ba1a',
content: 'https://twitter.com/prisma',
published: false,
title: 'Follow Prisma on Twitter',
wasCreated: 2022-03-29T19:14:11.375Z,
wasUpdated: 2022-03-29T19:14:11.375Z
}
]

测试写入

¥Testing Writes

然后你可以更改 test.ts 来尝试写入:

¥You can then alter your test.ts to try writes:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()

async function main() {
await prisma.$connect()
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice',
},
})
console.log(user)
}

main()
.catch(console.error)
.finally(() => prisma.$disconnect())

你应该看到一个用户已创建。

¥And you should see a user was created.

warning

如果你看到以下错误:

¥If you see the following error:

Prisma needs to perform transactions, which requires your MongoDB server to be run as a replica set. https://pris.ly/d/mongodb-replica-set

这意味着你的 MongoDB 数据库没有作为副本集运行。请参阅 上面的链接 了解解决此问题的步骤。

¥This means that your MongoDB database isn't running as a replica set. Refer to the link above for steps to resolve this issue.

升级你的应用

¥Upgrading your Application

现在你已经有了一个可用的 Prisma 客户端,你可以开始用最新的 Prisma 客户端查询替换 Prisma 客户端 1 查询。Prisma 客户端参考 是学习如何使用最新 Prisma 客户端的有用资源。

¥Now that you have a working Prisma Client, you can start replacing Prisma Client 1 queries with the latest Prisma Client queries. The Prisma Client Reference is a helpful resource for learning how to use the latest Prisma Client.

结论

¥Conclusion

我希望这篇简短的指南能够帮助你走上正确的道路。如果你有任何疑问或问题,请告诉我们。我们非常感谢你多年来的支持。

¥I hope this brief guide was helpful in getting you started on the right path. Let us know if you have any questions or issues. We really appreciate your support over the years.