Overview概述
Prisma is an open source Object Relational Mapper (ORM) for Node.js. It supports both JavaScript and TypeScript, but it is primarily used with TypeScript to help you write readable and type-safe code.Prisma是Node.js的开源对象关系映射器(ORM)。它支持JavaScript和TypeScript,但它主要与TypeScript一起使用,以帮助您编写可读且类型安全的代码。
Warning
MongoDB Support for Prisma ORM v7MongoDB支持Prisma ORM v7
The MongoDB Node.js driver does not yet support Prisma ORM version 7. Use the latest available version 6.x release of Prisma ORM when working with MongoDB.MongoDB Node.js驱动程序尚不支持Prisma ORM版本7。使用MongoDB时,请使用Prisma ORM的最新6x版本。
Schemas模式
Schemas help developers avoid data inconsistency issues over time by defining the structure of your collection's documents. While you can define a schema at the database level within MongoDB, Prisma lets you define a schema at the application level. Because the Prisma Client is aware of the schema, developers using the Prisma Client have access to auto-completing queries.模式通过定义集合文档的结构,帮助开发人员避免数据不一致问题。虽然您可以在MongoDB中的数据库级别定义模式,但Prisma允许您在应用程序级别定义模式。因为Prisma客户端知道模式,所以使用Prisma客户端的开发人员可以访问自动完成的查询。
Data Modeling数据建模
Generally, data that is accessed together should be stored together in a MongoDB collection. Prisma supports using embedded documents to keep data together. In use cases where you must store related data in separate MongoDB collections, you must include one document's 通常,一起访问的数据应该一起存储在MongoDB集合中。Prisma支持使用嵌入式文档将数据保存在一起。在必须将相关数据存储在单独的MongoDB集合中的用例中,必须在另一个文档中包含一个文档的_id field in another document. Prisma streamlines this process and assists you in organizing this related data, while also maintaining referential integrity of the data._id字段。Prisma简化了这一过程,并帮助您组织相关数据,同时保持数据的引用完整性。
When you use references to model relations between collections, you can add the 当您使用引用来建模集合之间的关系时,您可以将@relation attribute to your Prisma schema to enable Prisma Client to access those relations, emulate referential actions, and help maintain referential integrity.@relation属性添加到Prisma架构中,以使Prisma客户端能够访问这些关系、模拟引用操作并帮助维护引用完整性。
To learn more about efficient data modeling in MongoDB, see Reduce $lookup Operations in the MongoDB Server manual.要了解更多关于MongoDB中高效数据建模的信息,请参阅MongoDB服务器手册中的Reduce$lookup操作。
Schema Introspection图式反思
MongoDB has a flexible schema by default. When you introspect an existing MongoDB database by using the 默认情况下,MongoDB具有灵活的模式。当您使用prisma db pull command, Prisma samples up to 1000 random documents from each collection to infer the schema structure.prisma db pull命令对现有的MongoDB数据库进行自检时,prisma会从每个集合中随机采样多达1000个文档,以推断模式结构。
If your collection contains fields with inconsistent data types across documents, Prisma maps those fields to the 如果您的集合包含跨文档数据类型不一致的字段,Prisma会将这些字段映射到Json type and outputs a warning. Json类型并输出警告。This enables you to read all existing data, but it reduces type safety benefits. 这使您能够读取所有现有数据,但会降低类型安全效益。To resolve this, you can manually update the data to use consistent types, and then run 为了解决这个问题,您可以手动更新数据以使用一致的类型,然后再次运行prisma db pull again to regenerate the schema with proper type definitions. prisma db pull以使用正确的类型定义重新生成模式。For more information, see Troubleshooting Type Conflicts.有关更多信息,请参阅排除类型冲突。
Tutorial教程
This tutorial shows how to perform the following actions:本教程展示了如何执行以下操作:
Download an example Prisma application下载Prisma应用程序示例Configure your Prisma schema配置Prisma架构Create and populate a MongoDB database with sample data使用示例数据创建并填充MongoDB数据库Make the example application compatible with MongoDB使示例应用程序与MongoDB兼容Run the application运行应用程序
Verify the prerequisites验证先决条件
Before you begin this tutorial, ensure you have the following components prepared:在开始本教程之前,请确保您已准备好以下组件:
A MongoDB Atlas account with a configured cluster. To view instructions, see the MongoDB Get Started guide.一个配置了集群的MongoDB Atlas帐户。要查看说明,请参阅MongoDB入门指南。- Node.js
v16.20.1 or later.v16.20.1或更高版本。
Download the example application下载示例应用程序
Clone or download the example application from the Prisma examples repository.从Prisma示例存储库克隆或下载示例应用程序。
This example is a simple blog content management platform that uses a SQLite database. The following steps modify the application to use MongoDB instead of SQLite.这个例子是一个使用SQLite数据库的简单博客内容管理平台。以下步骤修改应用程序以使用MongoDB而不是SQLite。
Configure your Prisma schema配置Prisma架构
Navigate to the 导航到示例应用程序目录中的prisma/schema.prisma file in the example application directory. In the datasource db object of this file, set the provider field to "mongodb" and the url field to your Atlas connection URI.prisma/schema.prisma文件。在该文件的datasource db对象中,将provider字段设置为"mongodb",将url字段设置为Atlas连接URI。
In the 在同一文件的User model in the same file, change the id field type from Int to String and set the default value to auto(). User模型中,将id字段类型从Int更改为String,并将默认值设置为auto()。The id property must map to the MongoDB _id field. You must also instruct Prisma to set the data type for this property to ObjectId.id属性必须映射到MongoDB _id字段。您还必须指示Prisma将此属性的数据类型设置为ObjectId。
In the 在Post model, perform the same changes to the id field as you did in the User model. You must also change the authorId field type from Int to String and set the data type to ObjectId.Post模型中,对id字段执行与在User模型中相同的更改。您还必须将authorId字段类型从Int更改为String,并将数据类型设置为ObjectId。
Your 您的schema.prisma file should resemble the following:schema.prisma文件应类似于以下内容:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = "<your connection URI>"
}
model Post {
id String (auto()) ("_id") .ObjectId
createdAt DateTime (now())
updatedAt DateTime
title String
content String?
published Boolean (false)
viewCount Int (0)
author User (fields: [authorId], references: [id])
authorId String .ObjectId
}
model User {
id String (auto()) ("_id") .ObjectId
email String
name String?
posts Post[]
}
This schema defines separate 此模式在MongoDB数据库中定义了单独的User and Post collections in your MongoDB database, where each Post contains a reference to a User.User和Post集合,其中每个Post都包含对User的引用。
Once you have made these changes, navigate to the project directory in your terminal and run the following commands to install the necessary dependencies and generate the schema:完成这些更改后,导航到终端中的项目目录,并运行以下命令以安装必要的依赖关系并生成模式:
npm install
npx prisma generate
Note
If you make any further changes to the schema, you must re-run the 如果对模式进行任何进一步更改,则必须重新运行npx prisma generate command for the changes to take effect.npx prisma generate命令才能使更改生效。
Create and populate the MongoDB database创建并填充MongoDB数据库
To populate the database with sample data, run the 要用示例数据填充数据库,请通过运行以下命令在示例项目中运行prisma/seed.ts file in the example project by running the following command:prisma/seed.ts文件:
npx prisma db seed
This creates the 这将创建User and Post collections as defined by the schema.prisma file and populates them with sample data.schema.prisma文件定义的User和Post集合,并用示例数据填充它们。
Make the example application compatible with MongoDB使示例应用程序与MongoDB兼容
Navigate to the 导航到示例项目的src directory of the example project. In the pages/api/post/[id].ts and pages/api/publish/[id].ts files, replace all instances of Number(postId) with postId. src目录。在pages/api/post/[id].ts和pages/api/publish/[id].ts文件中,将Number(postId)的所有实例替换为postId。This is necessary because the 这是必要的,因为模式中的id fields in the schema are now of type String instead of Int.id字段现在的类型是String而不是Int。
Run the application运行应用程序
To start the application, run the following command from the project directory:要启动应用程序,请从项目目录运行以下命令:
npm run dev
Navigate to 导航到http://localhost:3000 in your web browser to view and run the application. You can use the application to create, draft, publish, and delete blog posts. http://localhost:3000在您的网络浏览器中查看和运行应用程序。您可以使用该应用程序创建、起草、发布和删除博客文章。You can reference the API route definitions in the 您可以引用示例项目的pages/api folder of the example project.pages/api文件夹中的API路由定义。
Troubleshooting Type Conflicts排除类型冲突
If your MongoDB collections contain fields that use inconsistent data types across documents, Prisma Client might throw errors when querying data that doesn't match the expected type from your schema.如果您的MongoDB集合包含在文档中使用不一致数据类型的字段,Prisma Client在查询与模式中的预期类型不匹配的数据时可能会抛出错误。
You can perform the following actions to address this:您可以执行以下操作来解决此问题:
Review the warnings and comments in your Prisma schema after running运行Prisma-db pull后,查看Prisma架构中的警告和注释,以识别使用冲突类型的字段。prisma db pullto identify fields that use conflicting types.Update your data to use consistent types across all documents in the collection.更新您的数据,以便在集合中的所有文档中使用一致的类型。Run再次运行prisma db pullagain to regenerate your schema that includes the corrected types.prisma db pull以重新生成包含更正类型的模式。
Alternatively, you can leave the field as type 或者,如果需要保持灵活性,可以将字段保留为Json if you need to maintain flexibility. However, this reduces the type safety benefits that Prisma provides.Json类型。然而,这降低了Prisma提供的类型安全优势。
Additional Resources其他资源
To learn more about Prisma, see the Prisma documentation.要了解有关Prisma的更多信息,请参阅Prisma文档。
To view and download a full version of the application in this tutorial, see the prisma-mongodb-nextjs-example GitHub repository.要查看和下载本教程中应用程序的完整版本,请参阅prisma mongodb-nextjs示例GitHub存储库。