TypeScriptとMongoDBを使用したデータベースクエリ
Prisma Clientで最初のクエリを記述する
Prisma Clientが生成されたので、データベースのデータを読み書きするためのクエリの記述を開始できます。このガイドの目的のために、Prisma Clientのいくつかの基本的な機能を試すために、プレーンなNode.jsスクリプトを使用します。
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',
},
],
},
]
また、allUsers
はPrisma Clientの生成された型のおかげで静的に型付けされていることにも注目してください。エディタで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を使って初めてデータベースに新しいデータを書き込みました 🚀