跳到主內容

使用 TypeScript 和 Prisma ORM 查詢您現有的 MongoDB 資料庫

使用 Prisma Client 編寫您的第一個查詢

生成 Prisma Client 後,您可以開始編寫查詢來讀取和寫入資料庫中的資料。在本指南中,您將使用一個簡單的 Node.js 指令碼來探索 Prisma Client 的一些基本功能。

如果您正在構建 REST API,可以在路由處理程式中使用 Prisma Client,根據傳入的 HTTP 請求讀取和寫入資料庫中的資料。如果您正在構建 GraphQL API,可以在解析器中使用 Prisma Client,根據傳入的查詢和變更操作讀取和寫入資料庫中的資料。

然而,為了本指南的目的,您將建立一個簡單的 Node.js 指令碼來學習如何使用 Prisma Client 向資料庫傳送查詢。一旦您瞭解了 API 的工作方式,就可以開始將其整合到您的實際應用程式程式碼中(例如 REST 路由處理程式或 GraphQL 解析器)。

建立一個名為 index.ts 的新檔案,並向其中新增以下程式碼

index.ts
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)
})

以下是程式碼片段不同部分的快速概覽

  1. @prisma/client Node 模組匯入 PrismaClient 建構函式
  2. 例項化 PrismaClient
  3. 定義一個名為 mainasync 函式,用於向資料庫傳送查詢
  4. 連線到資料庫
  5. 呼叫 main 函式
  6. 指令碼終止時關閉資料庫連線

main 函式中,新增以下查詢以從資料庫讀取所有 User 記錄並列印結果

index.ts
async function main() {
// ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
}

現在使用此命令執行程式碼

npx tsx index.ts

如果您內省了一個包含記錄的現有資料庫,查詢應該返回一個 JavaScript 物件陣列。

將資料寫入資料庫

您在上一節中使用的 findMany 查詢僅從資料庫中 讀取 資料(儘管它當時還是空的)。在本節中,您將學習如何編寫查詢以向 PostUserComment 表中 寫入 新記錄。

調整 main 函式,向資料庫傳送一個 create 查詢

index.ts
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.authorUser.posts 關聯欄位分別連線到另一條記錄。

請注意,您向 findMany 傳遞了 include 選項,這告訴 Prisma Client 在返回的 User 物件中包含 posts 關聯。

使用此命令執行程式碼

npx tsx index.ts

輸出應類似於這樣

[
{
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 變數上以觀察其型別。它應如下所示

const allUsers: (User & {
posts: Post[]
})[]

export type Post = {
id: number
title: string
body: string | null
published: boolean
authorId: number | null
}

該查詢將新記錄新增到了 UserPost 集合中

資訊

Prisma 模式中的 id 欄位對映到底層 MongoDB 資料庫中的 _id

User 集合

_idemailname
60cc9b0e001e3bfd00a6eddf"hello@prisma.com""Rich"

Post 集合

_idcreatedAttitlecontentpublishedauthorId
60cc9bad005059d6007f45dd2020-03-21T16:45:01.246Z"我的第一篇帖子"許多非常有趣的內容false60cc9b0e001e3bfd00a6eddf

注意Post 文件欄位中 authorId 的唯一識別符號引用了 User 集合中的 _id 文件欄位,這意味著 _id60cc9b0e001e3bfd00a6eddf 列因此指向資料庫中第一個(也是唯一一個)User 記錄。

在繼續下一節之前,您將使用 update 查詢向剛剛建立的 Post 記錄新增幾個評論。請按如下方式調整 main 函式

index.ts
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 })
}

現在使用與之前相同的命令執行程式碼

npx tsx index.ts

您將看到以下輸出

[
{
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 Client 將新資料寫入了您的資料庫 🚀

© . This site is unofficial and not affiliated with Prisma Data, Inc.