跳到主要內容

使用 JavaScript 和 Prisma ORM 查詢現有 CockroachDB 資料庫

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

生成 Prisma Client 後,您就可以開始編寫查詢來讀寫資料庫中的資料。

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

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

建立一個名為 index.js 的新檔案並新增以下程式碼

index.js
const { PrismaClient } = require('@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)
})
index.js
async function main() {
const allUsers = await prisma.user.findMany()
console.log(allUsers)
}

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

node index.js

如果您使用資料庫內省步驟中的 schema 建立了資料庫,查詢將列印一個空陣列,因為資料庫中還沒有 User 記錄。

[]

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

向資料庫寫入資料

您在上一節中使用的 findMany 查詢僅從資料庫中“讀取”資料。在本節中,您將學習如何編寫查詢以“寫入”新記錄到 PostUser 表中。

調整 main 函式以向資料庫傳送 create 查詢

index.js
async function main() {
await prisma.user.create({
data: {
name: 'Alice',
email: 'alice@prisma.io',
posts: {
create: { title: 'Hello World' },
},
profile: {
create: { bio: 'I like turtles' },
},
},
})

const allUsers = await prisma.user.findMany({
include: {
posts: true,
profile: true,
},
})
console.dir(allUsers, { depth: null })
}

此程式碼使用巢狀寫入查詢建立新的 User 記錄以及新的 PostProfile 記錄。User 記錄透過 Post.authorUser.postsProfile.userUser.profile 關係欄位分別與其他兩條記錄連線。

請注意,您將 include 選項傳遞給 findMany,它告訴 Prisma Client 在返回的 User 物件中包含 postsprofile 關係。

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

node index.js

在進入下一節之前,您將使用 update 查詢“釋出”您剛剛建立的 Post 記錄。如下調整 main 函式

index.js
async function main() {
const post = await prisma.post.update({
where: { title: 'Hello World' },
data: { published: true },
})
console.log(post)
}

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

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