Prisma ORM MongoDB 数据库连接器
本指南讨论使用 Prisma ORM 和 MongoDB 背后的概念,解释 MongoDB 与其他数据库提供商之间的共性和差异,并引导你完成配置应用以使用 Prisma ORM 与 MongoDB 集成的过程。
¥This guide discusses the concepts behind using Prisma ORM and MongoDB, explains the commonalities and differences between MongoDB and other database providers, and leads you through the process for configuring your application to integrate with MongoDB using Prisma ORM.
要将 Prisma ORM 与 MongoDB 连接,请参阅我们的 入门文档。
¥To connect Prisma ORM with MongoDB, refer to our Getting Started documentation.
什么是 MongoDB?
¥What is MongoDB?
MongoDB 是一个 NoSQL 数据库,以 BSON 格式存储数据,BSON 是一种类似 JSON 的文档格式,旨在以键值对的形式存储数据。它通常用于 JavaScript 应用开发,因为文档模型可以轻松映射到应用代码中的对象,并且内置对高可用性和水平扩展的支持。
¥MongoDB is a NoSQL database that stores data in BSON format, a JSON-like document format designed for storing data in key-value pairs. It is commonly used in JavaScript application development because the document model maps easily to objects in application code, and there is built in support for high availability and horizontal scaling.
MongoDB 将数据存储在集合中,不需要提前定义模式,就像处理关系数据库中的表一样。每个集合的结构也可以随着时间的推移而改变。这种灵活性可以允许数据模型的快速迭代,但这确实意味着使用 Prisma ORM 与 MongoDB 数据库配合使用时存在许多差异。
¥MongoDB stores data in collections that do not need a schema to be defined in advance, as you would need to do with tables in a relational database. The structure of each collection can also be changed over time. This flexibility can allow rapid iteration of your data model, but it does mean that there are a number of differences when using Prisma ORM to work with your MongoDB database.
与其他数据库提供商的共同点
¥Commonalities with other database providers
将 Prisma ORM 与 MongoDB 结合使用的某些方面与将 Prisma ORM 与关系数据库结合使用时相同。你仍然可以:
¥Some aspects of using Prisma ORM with MongoDB are the same as when using Prisma ORM with a relational database. You can still:
-
使用 Prisma 模式语言 为你的数据库建模
¥model your database with the Prisma Schema Language
-
使用
mongodb
数据库连接器 连接到你的数据库¥connect to your database, using the
mongodb
database connector -
如果你已经有 MongoDB 数据库,请对现有项目使用 内省
¥use Introspection for existing projects if you already have a MongoDB database
-
使用
db push
将架构中的更改推送到数据库¥use
db push
to push changes in your schema to the database -
在应用中使用 Prisma 客户端 根据 Prisma 架构以类型安全的方式查询数据库
¥use Prisma Client in your application to query your database in a type safe way based on your Prisma Schema
需要考虑的差异
¥Differences to consider
MongoDB 的基于文档的结构和灵活的模式意味着使用 Prisma ORM 与 MongoDB 在许多方面与使用关系数据库不同。你需要注意以下一些方面存在的差异:
¥MongoDB's document-based structure and flexible schema means that using Prisma ORM with MongoDB differs from using it with a relational database in a number of ways. These are some areas where there are differences that you need to be aware of:
-
定义 ID:MongoDB 文档有一个
_id
字段(通常包含 对象 ID)。Prisma ORM 不支持以_
开头的字段,因此需要使用@map
属性将其映射到 Prisma ORM 字段。欲了解更多信息,请参阅 在 MongoDB 中定义 ID。¥Defining IDs: MongoDB documents have an
_id
field (that often contains an ObjectID). Prisma ORM does not support fields starting with_
, so this needs to be mapped to a Prisma ORM field using the@map
attribute. For more information, see Defining IDs in MongoDB. -
迁移现有数据以匹配你的 Prisma 架构:在关系数据库中,所有数据都必须与你的架构匹配。如果你在迁移时更改架构中特定字段的类型,则所有数据也必须更新以匹配。相比之下,MongoDB 不强制执行任何特定模式,因此迁移时需要小心。欲了解更多信息,请参阅 如何将旧数据迁移到新模式。
¥Migrating existing data to match your Prisma schema: In relational databases, all your data must match your schema. If you change the type of a particular field in your schema when you migrate, all the data must also be updated to match. In contrast, MongoDB does not enforce any particular schema, so you need to take care when migrating. For more information, see How to migrate old data to new schemas.
-
Introspection 和 Prisma ORM 关系:当你内省现有 MongoDB 数据库时,你将获得一个没有关系的模式,并且需要手动添加缺少的关系。欲了解更多信息,请参阅 内省后如何添加缺失的关系。
¥Introspection and Prisma ORM relations: When you introspect an existing MongoDB database, you will get a schema with no relations and will need to add the missing relations in manually. For more information, see How to add in missing relations after Introspection.
-
过滤
null
和缺失字段:MongoDB 对将字段设置为null
和根本不设置字段进行了区分,这在关系数据库中是不存在的。Prisma ORM 目前没有表达这种区别,这意味着在过滤null
和缺失字段时需要小心。欲了解更多信息,请参阅 如何过滤null
和缺失字段¥Filtering for
null
and missing fields: MongoDB makes a distinction between setting a field tonull
and not setting it at all, which is not present in relational databases. Prisma ORM currently does not express this distinction, which means that you need to be careful when filtering fornull
and missing fields. For more information, see How to filter fornull
and missing fields -
启用复制:Prisma ORM 在内部使用 MongoDB 事务 来避免嵌套查询的部分写入。使用事务时,MongoDB 需要启用数据集复制。为此,你需要配置 副本集 — 这是一组维护相同数据集的 MongoDB 进程。请注意,仍然可以通过创建仅包含一个节点的副本集来使用单个数据库。如果你使用 MongoDB 的 阿特拉斯 托管服务,则会为你配置副本集,但如果你在本地运行 MongoDB,则需要自己设置副本集。有关更多信息,请参阅 MongoDB 的 部署副本集指南。
¥Enabling replication: Prisma ORM uses MongoDB transactions internally to avoid partial writes on nested queries. When using transactions, MongoDB requires replication of your data set to be enabled. To do this, you will need to configure a replica set — this is a group of MongoDB processes that maintain the same data set. Note that it is still possible to use a single database, by creating a replica set with only one node in it. If you use MongoDB's Atlas hosting service, the replica set is configured for you, but if you are running MongoDB locally you will need to set up a replica set yourself. For more information, see MongoDB's guide to deploying a replica set.
大型集合的性能注意事项
¥Performance considerations for large collections
问题
¥Problem
通过 Prisma 处理大型 MongoDB 集合时,某些操作可能会变得缓慢且耗费资源。特别是,需要扫描整个集合的操作(例如 count()
)可能会达到查询执行时间限制,并且随着数据集的增长会严重影响性能。
¥When working with large MongoDB collections through Prisma, certain operations can become slow and resource-intensive. In particular, operations that require scanning the entire collection, such as count()
, can hit query execution time limits and significantly impact performance as your dataset grows.
解决方案
¥Solution
要解决大型 MongoDB 集合的性能问题,请考虑以下方法:
¥To address performance issues with large MongoDB collections, consider the following approaches:
-
对于大型集合,请考虑使用 MongoDB 的
estimatedDocumentCount()
而不是count()
。此方法更快,因为它使用有关集合的元数据。你可以使用 Prisma 的runCommandRaw
方法执行此命令。¥For large collections, consider using MongoDB's
estimatedDocumentCount()
instead ofcount()
. This method is much faster as it uses metadata about the collection. You can use Prisma'srunCommandRaw
method to execute this command. -
对于经常访问的计数,请考虑实现计数器缓存。这涉及维护一个单独的文档,其中包含预先计算的计数,你可以在添加或删除文档时更新该计数。
¥For frequently accessed counts, consider implementing a counter cache. This involves maintaining a separate document with pre-calculated counts that you update whenever documents are added or removed.
如何将 Prisma ORM 与 MongoDB 结合使用
¥How to use Prisma ORM with MongoDB
本部分提供有关如何执行需要特定于 MongoDB 的步骤的任务的说明。
¥This section provides instructions for how to carry out tasks that require steps specific to MongoDB.
如何迁移现有数据以匹配你的 Prisma 架构
¥How to migrate existing data to match your Prisma schema
随着时间的推移迁移数据库是开发周期的重要组成部分。在开发过程中,你需要更新 Prisma 模式(例如,添加新字段),然后更新开发环境数据库中的数据,最终将更新后的模式和新数据推送到生产数据库。
¥Migrating your database over time is an important part of the development cycle. During development, you will need to update your Prisma schema (for example, to add new fields), then update the data in your development environment’s database, and eventually push both the updated schema and the new data to the production database.
使用 MongoDB 时,请注意,你的架构和数据库之间的“耦合”故意设计得比 SQL 数据库更不严格;MongoDB 不会强制执行该架构,因此你必须验证数据完整性。
¥When using MongoDB, be aware that the “coupling” between your schema and the database is purposefully designed to be less rigid than with SQL databases; MongoDB will not enforce the schema, so you have to verify data integrity.
这些更新架构和数据库的迭代任务可能会导致架构与数据库中的实际数据之间不一致。让我们看一下可能发生这种情况的一种场景,然后检查你和你的团队可以考虑处理这些不一致问题的几种策略。
¥These iterative tasks of updating the schema and the database can result in inconsistencies between your schema and the actual data in the database. Let’s look at one scenario where this can happen, and then examine several strategies for you and your team to consider for handling these inconsistencies.
设想:你需要包含用户的调用号码以及电子邮件。你当前的 schema.prisma
文件中有以下 User
模型:
¥Scenario: you need to include a phone number for users, as well as an email. You currently have the following User
model in your schema.prisma
file:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
}
你可以使用多种策略来迁移此架构:
¥There are a number of strategies you could use for migrating this schema:
-
"一经请求" 更新:通过此策略,你和你的团队同意可以根据需要对架构进行更新。但是,为了避免由于数据和架构之间不一致而导致迁移失败,团队中一致认为添加的任何新字段都明确定义为可选。
¥"On-demand" updates: with this strategy, you and your team have agreed that updates can be made to the schema as needed. However, in order to avoid migration failures due to inconsistencies between the data and schema, there is agreement in the team that any new fields added are explicitly defined as optional.
在上面的场景中,你可以将可选的
phoneNumber
字段添加到 Prisma 架构中的User
模型中:¥In our scenario above, you can add an optional
phoneNumber
field to theUser
model in your Prisma schema:prisma/schema.prismamodel User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
phoneNumber String?
}然后使用
npx prisma generate
命令重新生成 Prisma 客户端。¥Then regenerate your Prisma Client using the
npx prisma generate
command.接下来,更新你的应用以反映新字段,并重新部署你的应用。
¥Next, update your application to reflect the new field, and redeploy your app.
由于
phoneNumber
字段是可选字段,因此你仍然可以查询未定义调用号码的老用户。当应用的用户开始在新字段中输入调用号码时,数据库中的记录将更新 "一经请求"。¥As the
phoneNumber
field is optional, you can still query the old users where the phone number has not been defined. The records in the database will be updated "on demand" as the application's users begin to enter their phone number in the new field.另一种选择是在必填字段上添加默认值,例如:
¥Another option is to add a default value on a required field, for example:
prisma/schema.prismamodel User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
phoneNumber String @default("000-000-0000")
}那么当遇到缺失的
phoneNumber
时,该值将被强制转换为000-000-0000
。¥Then when you encounter a missing
phoneNumber
, the value will be coerced into000-000-0000
. -
"没有重大变化" 更新:该策略建立在第一个策略的基础上,你的团队进一步达成共识,即你不会重命名或删除字段,仅添加新字段,并且始终将新字段定义为可选。可以通过在 CI/CD 流程中添加检查来加强此策略,以验证架构不存在向后不兼容的更改。
¥"No breaking changes" updates: this strategy builds on the first one, with further consensus amongst your team that you don't rename or delete fields, only add new fields, and always define the new fields as optional. This policy can be reinforced by adding checks in the CI/CD process to verify that there are no backwards-incompatible changes to the schema.
-
"一次全部" 更新:此策略类似于关系数据库中的传统迁移,其中所有数据都会更新以反映新架构。在上面的场景中,你将创建一个脚本来将调用号码字段的值添加到数据库中的所有现有用户。然后,你可以将该字段设置为应用中的必填字段,因为架构和数据是一致的。
¥"All-at-once" updates: this strategy is similar to traditional migrations in relational databases, where all data is updated to reflect the new schema. In the scenario above, you would create a script to add a value for the phone number field to all existing users in your database. You can then make the field a required field in the application because the schema and the data are consistent.
内省后如何添加缺失的关系
¥How to add in missing relations after Introspection
内省现有 MongoDB 数据库后,你需要手动添加模型之间的关系。MongoDB 没有像关系数据库那样通过外键定义关系的概念。但是,如果 MongoDB 中有一个集合,其 "foreign-key-like" 字段与另一个集合的 ID 字段匹配,Prisma ORM 将允许你模拟集合之间的关系。
¥After introspecting an existing MongoDB database, you will need to manually add in relations between models. MongoDB does not have the concept of defining relations via foreign keys, as you would in a relational database. However, if you have a collection in MongoDB with a "foreign-key-like" field that matches the ID field of another collection, Prisma ORM will allow you to emulate relations between the collections.
例如,以具有两个集合 User
和 Post
的 MongoDB 数据库为例。这些集合中的数据具有以下格式,其中 userId
字段将用户链接到帖子:
¥As an example, take a MongoDB database with two collections, User
and Post
. The data in these collections has the following format, with a userId
field linking users to posts:
User
系列:
¥User
collection:
-
类型为
objectId
的_id
字段¥
_id
field with a type ofobjectId
-
类型为
string
的email
字段¥
email
field with a type ofstring
Post
系列:
¥Post
collection:
-
类型为
objectId
的_id
字段¥
_id
field with a type ofobjectId
-
类型为
string
的title
字段¥
title
field with a type ofstring
-
类型为
objectID
的userId
¥
userId
with a type ofobjectID
在使用 db pull
进行自省时,它被拉入 Prisma Schema,如下所示:
¥On introspection with db pull
, this is pulled in to the Prisma Schema as follows:
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
userId String @db.ObjectId
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
}
这缺少 User
和 Post
型号之间的关系。要解决此问题,请手动将 user
字段添加到 Post
模型,并使用 userId
作为 fields
值,将其链接到 User
模型,并使用 @relation
属性将其链接到 User
模型,并将 posts
字段作为后向关系链接到 User
模型:
¥This is missing the relation between the User
and Post
models. To fix this, manually add a user
field to the Post
model with a @relation
attribute using userId
as the fields
value, linking it to the User
model, and a posts
field to the User
model as the back relation:
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
title String
userId String @db.ObjectId
user User @relation(fields: [userId], references: [id])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
posts Post[]
}
有关如何在 Prisma ORM 中使用关系的更多信息,请参阅 我们的文档。
¥For more information on how to use relations in Prisma ORM, see our documentation.
如何过滤 null
和缺失字段
¥How to filter for null
and missing fields
要了解 MongoDB 如何区分 null
和缺失字段,请考虑带有可选 name
字段的 User
模型的示例:
¥To understand how MongoDB distinguishes between null
and missing fields, consider the example of a User
model with an optional name
field:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String
name String?
}
首先,尝试创建一条将 name
字段显式设置为 null
的记录。Prisma ORM 将按预期返回 name: null
:
¥First, try creating a record with the name
field explicitly set to null
. Prisma ORM will return name: null
as expected:
const createNull = await prisma.user.create({
data: {
email: 'user1@prisma.io',
name: null,
},
})
console.log(createNull)
{
id: '6242c4ae032bc76da250b207',
email: 'user1@prisma.io',
name: null
}
如果你直接检查你的 MongoDB 数据库,你还会看到一条新记录,name
设置为 null
:
¥If you check your MongoDB database directly, you will also see a new record with name
set to null
:
{
"_id": "6242c4af032bc76da250b207",
"email": "user1@prisma.io",
"name": null
}
接下来,尝试在不显式设置 name
字段的情况下创建记录:
¥Next, try creating a record without explicitly setting the name
field:
const createMissing = await prisma.user.create({
data: {
email: 'user2@prisma.io',
},
})
console.log(createMissing)
{
id: '6242c4ae032bc76da250b208',
email: 'user2@prisma.io',
name: null
}
Prisma ORM 仍然返回 name: null
,但是如果你直接查看数据库,你会发现该记录根本没有定义 name
字段:
¥Prisma ORM still returns name: null
, but if you look in the database directly you will see that the record has no name
field defined at all:
{
"_id": "6242c4af032bc76da250b208",
"email": "user2@prisma.io"
}
Prisma ORM 在这两种情况下返回相同的结果,因为我们目前没有办法在 MongoDB 中指定底层数据库中的 null
字段和根本未定义的字段之间的这种差异 - 请参阅 这个 Github 问题 了解更多信息。
¥Prisma ORM returns the same result in both cases, because we currently don't have a way to specify this difference in MongoDB between fields that are null
in the underlying database, and fields that are not defined at all — see this Github issue for more information.
这意味着你当前在过滤 null
和缺失字段时必须小心。过滤带有 name: null
的记录将仅返回第一条记录,而 name
显式设置为 null
:
¥This means that you currently have to be careful when filtering for null
and missing fields. Filtering for records with name: null
will only return the first record, with the name
explicitly set to null
:
const findNulls = await prisma.user.findMany({
where: {
name: null,
},
})
console.log(findNulls)
[
{
id: '6242c4ae032bc76da250b207',
email: 'user1@prisma.io',
name: null
}
]
这是因为 name: null
正在检查相等性,并且不存在的字段不等于 null
。
¥This is because name: null
is checking for equality, and a non-existing field isn't equal to null
.
要也包括缺失的字段,请使用 isSet
过滤器 显式搜索 null
或未设置的字段。这将返回两条记录:
¥To include missing fields as well, use the isSet
filter to explicitly search for fields which are either null
or not set. This will return both records:
const findNullOrMissing = await prisma.user.findMany({
where: {
OR: [
{
name: null,
},
{
name: {
isSet: false,
},
},
],
},
})
console.log(findNullOrMissing)
[
{
id: '6242c4ae032bc76da250b207',
email: 'user1@prisma.io',
name: null
},
{
id: '6242c4ae032bc76da250b208',
email: 'user2@prisma.io',
name: null
}
]
有关将 MongoDB 与 Prisma ORM 结合使用的更多信息
¥More on using MongoDB with Prisma ORM
开始将 MongoDB 与 Prisma ORM 结合使用的最快方法是参考我们的入门文档:
¥The fastest way to start using MongoDB with Prisma ORM is to refer to our Getting Started documentation:
这些教程将引导你完成连接到 MongoDB、推送架构更改以及使用 Prisma 客户端的过程。
¥These tutorials will take you through the process of connecting to MongoDB, pushing schema changes, and using Prisma Client.
更多参考信息可在 MongoDB 连接器文档 中找到。
¥Further reference information is available in the MongoDB connector documentation.
有关如何设置和管理 MongoDB 数据库的更多信息,请参阅 Prisma 数据指南。
¥For more information on how to set up and manage a MongoDB database, see the Prisma Data Guide.
示例
¥Example
要连接到 MongoDB 服务器,请在 Prisma 模式 中配置 datasource
块:
¥To connect to a MongoDB server, configure the datasource
block in your Prisma Schema:
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
传递到 datasource
块的字段是:
¥The fields passed to the datasource
block are:
-
provider
:指定mongodb
数据源连接器。¥
provider
: Specifies themongodb
data source connector. -
url
:指定 MongoDB 服务器的 连接网址。在本例中,使用环境变量 提供连接 URL。¥
url
: Specifies the connection URL for the MongoDB server. In this case, an environment variable is used to provide the connection URL.
MongoDB 数据库连接器使用事务来支持嵌套写入。事务需要 副本集 部署。部署副本集的最简单方法是使用 阿特拉斯。开始使用是免费的。
¥The MongoDB database connector uses transactions to support nested writes. Transactions require a replica set deployment. The easiest way to deploy a replica set is with Atlas. It's free to get started.
连接详情
¥Connection details
连接网址
¥Connection URL
可以通过不同的方式配置 MongoDB 连接 URL,具体取决于你托管数据库的方式。标准配置由以下组件组成:
¥The MongoDB connection URL can be configured in different ways depending on how you are hosting your database. The standard configuration is made up of the following components:
基本 URL 和路径
¥Base URL and path
连接 URL 的基本 URL 和路径部分由你的身份验证凭据组成,后跟主机(以及可选的端口号)和数据库。
¥The base URL and path sections of the connection URL are made up of your authentication credentials followed by the host (and optionally, a port number) and database.
mongodb://USERNAME:PASSWORD@HOST/DATABASE
以下组件构成数据库的基本 URL:
¥The following components make up the base URL of your database:
名称 | 占位符 | 描述 |
---|---|---|
用户 | USERNAME | 你的数据库用户的名称,例如 janedoe |
密码 | PASSWORD | 你的数据库用户的密码 |
主持人 | HOST | 运行 mongod 实例的主机。如果你正在运行分片集群,这将是 mongos 实例。这可以是主机名、IP 地址或 UNIX 域套接字。 |
港口 | PORT | 数据库服务器运行的端口,例如 1234 。如果未提供,则使用默认的 27017 。 |
数据库 | DATABASE | 要使用的数据库的名称。如果未指定但设置了 authSource 选项,则使用 authSource 数据库名称。如果连接字符串中的数据库和 authSource 选项均未指定,则默认为 admin |
你必须 对特殊字符进行百分比编码。
¥You must percentage-encode special characters.
参数
¥Arguments
连接 URL 也可以带参数。以下示例设置三个参数:
¥A connection URL can also take arguments. The following example sets three arguments:
-
ssl
连接¥An
ssl
connection -
一个
connectTimeoutMS
¥A
connectTimeoutMS
-
还有
maxPoolSize
¥And the
maxPoolSize
mongodb://USERNAME:PASSWORD@HOST/DATABASE?ssl=true&connectTimeoutMS=5000&maxPoolSize=50
有关连接字符串参数的完整列表,请参阅 MongoDB 连接字符串文档。没有 Prisma ORM 特定的参数。
¥Refer to the MongoDB connection string documentation for a complete list of connection string arguments. There are no Prisma ORM-specific arguments.
使用 ObjectId
¥Using ObjectId
MongoDB 文档的 _id
字段包含 ObjectId 是常见的做法:
¥It is common practice for the _id
field of a MongoDB document to contain an ObjectId:
{
"_id": { "$oid": "60d599cb001ef98000f2cad2" },
"createdAt": { "$date": { "$numberLong": "1624611275577" } },
"email": "ella@prisma.io",
"name": "Ella",
"role": "ADMIN"
}
映射到底层数据库中 ObjectId
的任何字段(最常见的是 ID 和关系标量字段):
¥Any field (most commonly IDs and relation scalar fields) that maps to an ObjectId
in the underlying database:
-
必须是
String
或Bytes
类型¥Must be of type
String
orBytes
-
必须包含
@db.ObjectId
属性¥Must include the
@db.ObjectId
attribute -
可以选择使用
@default(auto())
在文档创建时自动生成有效的ObjectId
¥Can optionally use
@default(auto())
to auto-generate a validObjectId
on document creation
以下是使用 String
的示例:
¥Here is an example that uses String
:
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
// Other fields
}
这是使用 Bytes
的另一个示例:
¥And here is another example that uses Bytes
:
model User {
id Bytes @id @default(auto()) @map("_id") @db.ObjectId
// Other fields
}
也可以看看:在 MongoDB 中定义 ID 字段
¥See also: Defining ID fields in MongoDB
生成 ObjectId
¥Generating ObjectId
要在应用中生成有效的 ObjectId
(用于测试目的或手动设置 ID 字段值),请使用 bson
包。
¥To generate a valid ObjectId
(for testing purposes or to manually set an ID field value) in your application, use the bson
package.
npm install --save bson
import { ObjectId } from 'bson'
const id = new ObjectId()
与关系数据库连接器的差异
¥Differences to connectors for relational databases
本节介绍 MongoDB 连接器与关系数据库的 Prisma ORM 连接器的不同之处。
¥This section covers ways in which the MongoDB connector differs from Prisma ORM connectors for relational databases.
不支持 Prisma Migrate
¥No support for Prisma Migrate
目前,没有计划添加对 Prisma 迁移 的支持,因为 MongoDB 项目不依赖于内部模式,需要使用额外的工具来管理更改。@unique
索引的管理是通过 db push
实现的。
¥Currently, there are no plans to add support for Prisma Migrate as MongoDB projects do not rely on internal schemas where changes need to be managed with an extra tool. Management of @unique
indexes is realized through db push
.
不支持 @@id
和 autoincrement()
¥No support for @@id
and autoincrement()
不支持 @@id
属性(多个字段的 ID),因为 MongoDB 中的主键始终位于模型的 _id
字段上。
¥The @@id
attribute (an ID for multiple fields) is not supported because primary keys in MongoDB are always on the _id
field of a model.
不支持 autoincrement()
函数(创建递增的 @id
值),因为 autoincrement()
不适用于 MongoDB 中 _id
字段所具有的 ObjectID
类型。
¥The autoincrement()
function (which creates incrementing @id
values) is not supported because autoincrement()
does not work with the ObjectID
type that the _id
field has in MongoDB.
循环引用和引用动作
¥Cyclic references and referential actions
如果你的模型中有循环引用(来自自关系或模型之间的关系循环),并且你使用 参考行动,则必须设置 NoAction
的引用操作以防止操作无限循环。
¥If you have cyclic references in your models, either from self-relations or a cycle of relations between models, and you use referential actions, you must set a referential action of NoAction
to prevent an infinite loop of actions.
详细信息请参见 参考动作的特殊规则。
¥See Special rules for referential actions for more details.
副本集配置
¥Replica set configuration
MongoDB 仅允许你在副本集上启动事务。Prisma ORM 在内部使用事务来避免嵌套查询的部分写入。这意味着我们继承了需要配置副本集的要求。
¥MongoDB only allows you to start a transaction on a replica set. Prisma ORM uses transactions internally to avoid partial writes on nested queries. This means we inherit the requirement of needing a replica set configured.
当你尝试在未配置副本集的部署上使用 Prisma ORM 的 MongoDB 连接器时,Prisma ORM 显示消息 Error: Transactions are not supported by this deployment
。错误消息全文如下:
¥When you try to use Prisma ORM's MongoDB connector on a deployment that has no replica set configured, Prisma ORM shows the message Error: Transactions are not supported by this deployment
. The full text of the error message is the following:
PrismaClientUnknownRequestError2 [PrismaClientUnknownRequestError]:
Invalid `prisma.post.create()` invocation in
/index.ts:9:21
6 await prisma.$connect()
7
8 // Create the first post
→ 9 await prisma.post.create(
Error in connector: Database error. error code: unknown, error message: Transactions are not supported by this deployment
at cb (/node_modules/@prisma/client/runtime/index.js:34804:17)
at processTicksAndRejections (internal/process/task_queues.js:97:5) {
clientVersion: '3.xx.0'
}
要解决此问题,我们建议你将部署更改为配置了副本集的部署。
¥To resolve this, we suggest you change your deployment to one with a replica set configured.
一种简单的方法是使用 MongoDB 阿特拉斯 启动一个具有开箱即用的副本集支持的免费实例。
¥One simple way for this is to use MongoDB Atlas to launch a free instance that has replica set support out of the box.
还可以选择使用本指南在本地运行副本集:https://www.mongodb.com/docs/manual/tutorial/convert-standalone-to-replica-set
¥There's also an option to run the replica set locally with this guide: https://www.mongodb.com/docs/manual/tutorial/convert-standalone-to-replica-set
MongoDB 和 Prisma 架构之间的类型映射
¥Type mapping between MongoDB and the Prisma schema
MongoDB 连接器将 标量类型 从 Prisma ORM 数据模型 映射到 MongoDB 的原生列类型,如下所示:
¥The MongoDB connector maps the scalar types from the Prisma ORM data model to MongoDB's native column types as follows:
或者,请参阅 Prisma 架构参考 了解按 Prisma 类型组织的类型映射。
¥Alternatively, see Prisma schema reference for type mappings organized by Prisma type.
从 Prisma ORM 到 MongoDB 的原生类型映射
¥Native type mapping from Prisma ORM to MongoDB
Prisma ORM | MongoDB |
---|---|
String | string |
Boolean | bool |
Int | int |
BigInt | long |
Float | double |
Decimal | 目前不支持 |
DateTime | timestamp |
Bytes | binData |
Json |
目前不支持的 MongoDB 类型:
¥MongoDB types that are currently unsupported:
-
Decimal128
-
Undefined
-
DBPointer
-
Null
-
Symbol
-
MinKey
-
MaxKey
-
Object
-
Javascript
-
JavascriptWithScope
-
Regex
Introspection 上从 MongoDB 到 Prisma ORM 类型的映射
¥Mapping from MongoDB to Prisma ORM types on Introspection
当内省 MongoDB 数据库时,Prisma ORM 使用相关的 标量类型。一些特殊类型还获得额外的原生类型注释:
¥When introspecting a MongoDB database, Prisma ORM uses the relevant scalar types. Some special types also get additional native type annotations:
MongoDB(类型 | 别名) | Prisma ORM | 支持的 | 原生数据库类型属性 | 注意 |
---|---|---|---|---|
objectId | String | ✔️ | @db.ObjectId |
内省 添加了 Unsupported
字段尚不支持的原生数据库类型:
¥Introspection adds native database types that are not yet supported as Unsupported
fields:
model Example {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
regex Unsupported("RegularExpression")
}