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

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

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

コードスニペットの各部分の概要は以下の通りです

  1. `@prisma/client` ノードモジュールから `PrismaClient` コンストラクタをインポートする
  2. `PrismaClient` をインスタンス化する
  3. データベースにクエリを送信するための `main` という名前の `async` 関数を定義する
  4. データベースに接続する
  5. `main` 関数を呼び出す
  6. スクリプトが終了したらデータベース接続を閉じる

`main` 関数内に、データベースからすべての `User` レコードを読み込み、結果を出力する以下のクエリを追加します

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

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

node index.js

レコードを含む既存のデータベースをイントロスペクションした場合、クエリはJavaScriptオブジェクトの配列を返すはずです。

データベースにデータを書き込む

前のセクションで使用した `findMany` クエリは、データベースからデータを読み取るだけでした(まだ空でしたが)。このセクションでは、`Post`、`User`、`Comment` テーブルに新しいレコードを書き込むクエリの作成方法を学びます。

`main` 関数を調整して、データベースに `create` クエリを送信します

index.js
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` のリレーションフィールドを介して他のレコードに接続されています。

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

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

node index.js

出力は以下のようになるはずです

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

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

情報

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

Userコレクション

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

Postコレクション

_idcreatedAttitlecontentpublishedauthorId
60cc9bad005059d6007f45dd2020-03-21T16:45:01.246Z"最初の投稿"本当にたくさんの興味深い内容false60cc9b0e001e3bfd00a6eddf

: `Post` の `authorId` ドキュメントフィールド内のユニークな識別子は、`User` コレクションの `_id` ドキュメントフィールドを参照しています。これは、`_id` の値 `60cc9b0e001e3bfd00a6eddf` のカラムがデータベース内の最初の(そして唯一の)`User` レコードを指すことを意味します。

次のセクションに進む前に、`update` クエリを使用して、先ほど作成した `Post` レコードにコメントをいくつか追加します。`main` 関数を次のように調整します

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

これまでと同じコマンドを使用してコードを実行します

node index.js

以下の出力が表示されます

[
{
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.