使用 TypeScript 和 Prisma ORM 查询现有的 MongoDB 数据库
使用 Prisma 客户端编写你的第一个查询
¥Write your first query with Prisma Client
现在你已经生成了 Prisma 客户端,你可以开始编写查询以在数据库中读取和写入数据。出于本指南的目的,你将使用简单的 Node.js 脚本来探索 Prisma Client 的一些基本功能。
¥Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client.
如果你正在构建 REST API,则可以在路由处理程序中使用 Prisma Client 根据传入的 HTTP 请求在数据库中读取和写入数据。如果你正在构建 GraphQL API,则可以在解析器中使用 Prisma Client 根据传入查询和突变在数据库中读取和写入数据。
¥If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations.
然而,就本指南而言,你只需创建一个简单的 Node.js 脚本来了解如何使用 Prisma Client 将查询发送到数据库。一旦你了解了 API 的工作原理,你就可以开始将其集成到实际的应用代码中(例如 REST 路由处理程序或 GraphQL 解析器)。
¥For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers).
创建一个名为 index.ts
的新文件并添加以下代码:
¥Create a new file named index.ts
and add the following code to it:
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
以下是代码片段不同部分的快速概述:
¥Here's a quick overview of the different parts of the code snippet:
-
从
@prisma/client
节点模块导入PrismaClient
构造函数¥Import the
PrismaClient
constructor from the@prisma/client
node module -
实例化
PrismaClient
¥Instantiate
PrismaClient
-
定义一个名为
main
的async
函数来向数据库发送查询¥Define an
async
function namedmain
to send queries to the database -
连接到数据库
¥Connect to the database
-
调用
main
函数¥Call the
main
function -
脚本终止时关闭数据库连接
¥Close the database connections when the script terminates
在 main
函数中,添加以下查询以从数据库读取所有 User
记录并打印结果:
¥Inside the main
function, add the following query to read all User
records from the database and print the result:
async function main() {
// ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
}
现在使用以下命令运行代码:
¥Now run the code with this command:
npx tsx index.ts
如果你内省了包含记录的现有数据库,则查询应返回 JavaScript 对象数组。
¥If you introspected an existing database with records, the query should return an array of JavaScript objects.
将数据写入数据库
¥Write data into the database
你在上一节中使用的 findMany
查询仅从数据库中读取数据(尽管它仍然是空的)。在本节中,你将学习如何编写查询以将新记录写入 Post
、User
和 Comment
表中。
¥The findMany
query you used in the previous section only reads data from the database (although it was still empty). In this section, you'll learn how to write a query to write new records into the Post
, User
and Comment
tables.
调整 main
函数以向数据库发送 create
查询:
¥Adjust the main
function to send a create
query to the database:
async function main() {
await prisma.user.create({
data: {
name: 'Rich',
email: 'hello@prisma.com',
posts: {
create: {
title: 'My first post',
body: 'Lots of really interesting stuff',
slug: 'my-first-post',
},
},
},
})
const allUsers = await prisma.user.findMany({
include: {
posts: true,
},
})
console.dir(allUsers, { depth: null })
}
此代码使用 嵌套写入 查询创建一条新的 User
记录以及一条新的 Post
。User
记录分别通过 Post.author
↔ User.posts
关系字段 连接到另一条记录。
¥This code creates a new User
record together with a new Post
using a nested write query. The User
record is connected to the other one via the Post.author
↔ User.posts
relation fields respectively.
请注意,你将 include
选项传递给 findMany
,这告诉 Prisma 客户端在返回的 User
对象上包含 posts
关系。
¥Notice that you're passing the include
option to findMany
which tells Prisma Client to include the posts
relations on the returned User
objects.
使用以下命令运行代码:
¥Run the code with this command:
npx tsx index.ts
输出应类似于以下内容:
¥The output should look similar to this:
[
{
id: '60cc9b0e001e3bfd00a6eddf',
email: 'hello@prisma.com',
name: 'Rich',
posts: [
{
id: '60cc9bad005059d6007f45dd',
slug: 'my-first-post',
title: 'My first post',
body: 'Lots of really interesting stuff',
userId: '60cc9b0e001e3bfd00a6eddf',
},
],
},
]
另请注意,由于 Prisma Client 生成的类型,allUsers
是静态类型的。你可以通过将鼠标悬停在编辑器中的 allUsers
变量上来观察类型。应输入如下:
¥Also note that allUsers
is statically typed thanks to Prisma Client's generated types. You can observe the type by hovering over the allUsers
variable in your editor. It should be typed as follows:
const allUsers: (User & {
posts: Post[]
})[]
export type Post = {
id: number
title: string
body: string | null
published: boolean
authorId: number | null
}
该查询向 User
和 Post
集合添加了新记录:
¥The query added new records to the User
and the Post
collections:
Prisma 架构中的 id
字段映射到底层 MongoDB 数据库中的 _id
。
¥The id
field in the Prisma schema maps to _id
in the underlying MongoDB database.
用户集合
¥User collection
_ID | name | |
---|---|---|
60cc9b0e001e3bfd00a6eddf | "hello@prisma.com" | "Rich" |
帖子集合
¥Post collection
_ID | createdAt | title | content | published | authorId |
---|---|---|---|---|---|
60cc9bad005059d6007f45dd | 2020-03-21T16:45:01.246Z | "My first post" | Lots of really interesting stuff | false | 60cc9b0e001e3bfd00a6eddf |
注意:
Post
上的authorId
文档字段中的唯一标识符引用User
集合中的_id
文档字段,这意味着_id
值60cc9b0e001e3bfd00a6eddf
列因此引用数据库中的第一个(也是唯一的)User
记录。¥Note: The unique identifier in the
authorId
document field onPost
reference the_id
document field in theUser
collection, meaning the_id
value60cc9b0e001e3bfd00a6eddf
column therefore refers to the first (and only)User
record in the database.
在继续下一部分之前,你将向刚刚使用 update
查询创建的 Post
记录添加一些注释。调整 main
功能如下:
¥Before moving on to the next section, you'll add a couple of comments to the Post
record you just created using an update
query. Adjust the main
function as follows:
async function main() {
await prisma.post.update({
where: {
slug: 'my-first-post',
},
data: {
comments: {
createMany: {
data: [
{ comment: 'Great post!' },
{ comment: "Can't wait to read more!" },
],
},
},
},
})
const posts = await prisma.post.findMany({
include: {
comments: true,
},
})
console.dir(posts, { depth: Infinity })
}
现在使用与之前相同的命令运行代码:
¥Now run the code using the same command as before:
npx tsx index.ts
你将看到以下输出:
¥You will see the following output:
[
{
id: '60cc9bad005059d6007f45dd',
slug: 'my-first-post',
title: 'My first post',
body: 'Lots of really interesting stuff',
userId: '60cc9b0e001e3bfd00a6eddf',
comments: [
{
id: '60cca420008a21d800578793',
postId: '60cca40300af8bf000f6ca99',
comment: 'Great post!',
},
{
id: '60cca420008a21d800578794',
postId: '60cca40300af8bf000f6ca99',
comment: "Can't wait to try this!",
},
],
},
]
太棒了,你刚刚使用 Prisma 客户端第一次将新数据写入数据库 🚀
¥Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀