使用 TypeScript 和 MongoDB 查詢資料庫
使用 Prisma Client 編寫您的第一個查詢
生成 Prisma Client 後,您可以開始編寫查詢來讀取和寫入資料庫中的資料。為了本指南的目的,您將使用一個簡單的 Node.js 指令碼來探索 Prisma Client 的一些基本功能。
建立一個名為 index.ts 的新檔案,並將以下程式碼新增到其中
import { PrismaClient } from './generated/prisma'
const prisma = new PrismaClient()
async function main() {
// ... you will write your Prisma Client queries here
}
main()
.catch(async (e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
以下是程式碼片段不同部分的快速概覽
- 從
@prisma/client節點模組匯入PrismaClient建構函式 - 例項化
PrismaClient - 定義一個名為
main的async函式來向資料庫傳送查詢 - 連線到資料庫
- 呼叫
main函式 - 指令碼終止時關閉資料庫連線
在 main 函式內部,新增以下查詢以從資料庫讀取所有 User 記錄並列印結果
async function main() {
// ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
}
現在使用此命令執行程式碼
npx tsx index.ts
這將列印一個空陣列,因為資料庫中還沒有 User 記錄
[]
將資料寫入資料庫
您在上一節中使用的 findMany 查詢僅從資料庫中讀取資料(儘管當時是空的)。在本節中,您將學習如何編寫查詢以將新記錄寫入 Post、User 和 Comment 表。
調整 main 函式以向資料庫傳送 create 查詢
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 關係欄位分別與其他記錄連線。
請注意,您正在將 include 選項傳遞給 findMany,它會告訴 Prisma Client 在返回的 User 物件中包含 posts 關係。
使用此命令執行程式碼
npx tsx index.ts
輸出應如下所示
[
{
id: '60cc9b0e001e3bfd00a6eddf',
email: 'hello@prisma.com',
name: 'Rich',
address: null,
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
}
此查詢將新記錄新增到了 User 和 Post 表中
使用者
| id | 電子郵件 | 名稱 |
|---|---|---|
60cc9b0e001e3bfd00a6eddf | "hello@prisma.com" | "Rich" |
帖子
| id | 建立時間 | 標題 | 內容 | 已釋出 | 作者 ID |
|---|---|---|---|---|---|
60cc9bad005059d6007f45dd | 2020-03-21T16:45:01.246Z | "我的第一個帖子" | 很多非常有趣的東西 | false | 60cc9b0e001e3bfd00a6eddf |
注意:
Post表中authorId列的唯一 ID 引用User表的id列,這意味著id值為60cc9b0e001e3bfd00a6eddf的列因此指的是資料庫中的第一個(也是唯一一個)User記錄。
在進入下一節之前,您將使用 update 查詢向剛剛建立的 Post 記錄新增幾條評論。將 main 函式調整如下
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 首次將新資料寫入資料庫 🚀