メインコンテンツにスキップ

既存のMongoDBデータベースをTypeScriptとPrisma ORMでクエリする

Prisma Clientで最初のクエリを記述する

Prisma Clientが生成されたので、データベース内のデータを読み書きするためのクエリを記述できるようになりました。このガイドの目的のために、Prisma Clientのいくつかの基本的な機能を探索するために、プレーンなNode.jsスクリプトを使用します。

REST APIを構築している場合、Prisma Clientをルートハンドラで使用して、受信HTTPリクエストに基づいてデータベースのデータを読み書きできます。GraphQL APIを構築している場合、Prisma Clientをリゾルバで使用して、受信クエリとミューテーションに基づいてデータベースのデータを読み書きできます。

しかし、このガイドの目的のためには、Prisma Clientを使用してデータベースにクエリを送信する方法を学ぶために、プレーンなNode.jsスクリプトを作成するだけです。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. データベースにクエリを送信するために、mainという名前のasync関数を定義します
  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クエリは、データベースからデータを読み取るだけでした(まだ空でしたが)。このセクションでは、PostUser、およびCommentテーブルに新しいレコードを書き込むためのクエリを記述する方法を学びます。

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リレーションフィールドを介して、もう一方に接続されます。

findManyincludeオプションを渡していることに注意してください。これは、返されるUserオブジェクトにpostsリレーションを含めるようにPrisma Clientに指示するものです。

このコマンドでコードを実行します

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',
},
],
},
]

また、allUsersPrisma Clientの生成された型のおかげで静的に型付けされていることにも注意してください。エディタでallUsers変数にカーソルを合わせると型を確認できます。次のように型付けされているはずです。

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

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

このクエリにより、UserおよびPostコレクションに新しいレコードが追加されました

情報

Prismaスキーマのidフィールドは、基盤となるMongoDBデータベースの_idにマッピングされます。

User コレクション

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

Post コレクション

_idcreatedAttitlecontentpublishedauthorId
60cc9bad005059d6007f45dd2020-03-21T16:45:01.246Z"My first post"たくさんの非常に興味深い内容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を使って初めてデータベースに新しいデータを書き込みました🚀

© . All rights reserved.