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

JavaScriptとMongoDBを使用してデータベースをクエリする

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

Prisma Clientを生成したら、データベースへのデータの読み書きを行うクエリの記述を開始できます。このガイドでは、Prisma Clientの基本的な機能を試すために、プレーンなNode.jsスクリプトを使用します。

`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

データベースに`User`レコードがまだないため、空の配列が出力されます

[]

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

前のセクションで使用した`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オプションを渡していることに注目してください。これは、Prisma Clientに返されるUserオブジェクトにpostsリレーションを含めるように指示するものです。

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

node index.js

出力は次のようになります

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

クエリにより、`User`テーブルと`Post`テーブルに新しいレコードが追加されました

User

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

Post

idcreatedAttitlecontentpublishedauthorId
60cc9bad005059d6007f45dd2020-03-21T16:45:01.246Z"My first post"本当に興味深い内容が盛りだくさんfalse60cc9b0e001e3bfd00a6eddf

: `Post`テーブルの`authorId`列にあるユニークなIDは、`User`テーブルの`id`列を参照しています。したがって、`id`値`60cc9b0e001e3bfd00a6eddf`は、データベース内の最初の(かつ唯一の)`User`レコードを指します。

次のセクションに進む前に、先ほど作成した`Post`レコードに`update`クエリを使用してコメントをいくつか追加します。`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.