JavaScript
MongoDB

Write your first query with Prisma Client

Now that you have generated Prisma Client, you can start writing queries to read and write data in your database. For the purpose of this guide, you'll use a plain Node.js script to explore some basic features of Prisma Client.

If you're building a REST API, you can use Prisma Client in your route handlers to read and write data in the database based on incoming HTTP requests. If you're building a GraphQL API, you can use Prisma Client in your resolvers to read and write data in the database based on incoming queries and mutations.

For the purpose of this guide however, you'll just create a plain Node.js script to learn how to send queries to your database using Prisma Client. Once you have an understanding of how the API works, you can start integrating it into your actual application code (e.g. REST route handlers or GraphQL resolvers).

Create a new file named index.ts and add the following code to it:

index.ts
1import { PrismaClient } from '@prisma/client'
2
3const prisma = new PrismaClient()
4
5async function main() {
6 // Connect the client
7 await prisma.$connect()
8 // ... you will write your Prisma Client queries here
9}
10
11main()
12 .catch((e) => {
13 throw e
14 })
15 .finally(async () => {
16 await prisma.$disconnect()
17 })

Create a new file named index.js and add the following code to it:

index.js
1const { PrismaClient } = require('@prisma/client')
2
3const prisma = new PrismaClient()
4
5async function main() {
6 // Connect the client
7 await prisma.$connect()
8 // ... you will write your Prisma Client queries here
9}
10
11main()
12 .catch((e) => {
13 throw e
14 })
15 .finally(async () => {
16 await prisma.$disconnect()
17 })

Here's a quick overview of the different parts of the code snippet:

  1. Import the PrismaClient constructor from the @prisma/client node module
  2. Instantiate PrismaClient
  3. Define an async function named main to send queries to the database
  4. Connect to the database
  5. Call the main function
  6. Close the database connections when the script terminates

Inside the main function, add the following query to read all User records from the database and print the result:

index.ts
1async function main() {
2 // Connect the client
3 await prisma.$connect()
4 // ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
7}
index.js
1async function main() {
2 // Connect the client
3 await prisma.$connect()
- // ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
7}

Now run the code with this command:

$npx ts-node index.ts
$node index.js

This should print an empty array because there are no User records in the database yet:

[]

Write data into the database

The findMany query you used in the previous section only reads data from the database (although it was still empty). In this section, you'll learn how to write a query to write new records into the Post, User and Comment tables.

Adjust the main function to send a create query to the database:

index.ts
1async function main() {
2 await prisma.$connect()
3
4 await prisma.user.create({
5 data: {
6 name: 'Rich',
7 email: 'hello@prisma.com',
8 posts: {
9 create: {
10 title: 'My first post',
11 body: 'Lots of really interesting stuff',
12 slug: 'my-first-post',
13 },
14 },
15 },
16 })
17
18 const allUsers = await prisma.user.findMany({
19 include: {
20 posts: true,
21 },
22 })
23 console.dir(allUsers, { depth: null })
24}
index.js
1async function main() {
2 await prisma.$connect()
3
4 await prisma.user.create({
5 data: {
6 name: 'Rich',
7 email: 'hello@prisma.com',
8 posts: {
9 create: {
10 title: 'My first post',
11 body: 'Lots of really interesting stuff',
12 slug: 'my-first-post',
13 },
14 },
15 },
16 })
17
18 const allUsers = await prisma.user.findMany({
19 include: {
20 posts: true,
21 },
22 })
23 console.dir(allUsers, { depth: null })
24}

This code creates a new User record together with a new Post using a nested write query. The User record is connected to the other one via the Post.authorUser.posts relation fields respectively.

Notice that you're passing the include option to findMany which tells Prisma Client to include the posts relations on the returned User objects.

Run the code with this command:

$npx ts-node index.ts
$node index.js

The output should look similar to this:

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

Also note that allUsers is statically typed thanks to Prisma Client's generated types. You can observe the type by hovering over the allUsers variable in your editor. It should be typed as follows:

const allUsers: (User & {
posts: Post[]
})[]
export type Post = {
id: number
title: string
body: string | null
published: boolean
authorId: number | null
}

The query added new records to the User and the Post collections:

The id field in the Prisma schema maps to _id in the underlying MongoDB database.

User collection

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

Post collection

_idcreatedAttitlecontentpublishedauthorId
60cc9bad005059d6007f45dd2020-03-21T16:45:01.246Z"My first post"Lots of really interesting stufffalse60cc9b0e001e3bfd00a6eddf

Note: The unique identifier in the authorId document field on Post reference the _id document field in the User collection, meaning the _id value 60cc9b0e001e3bfd00a6eddf column therefore refers to the first (and only) User record in the database.

Before moving on to the next section, you'll add a couple of comments to the Post record you just created using an update query. Adjust the main function as follows:

index.ts
1async function main() {
2 await prisma.post.update({
3 where: {
4 slug: 'my-first-post',
5 },
6 data: {
7 comments: {
8 createMany: {
9 data: [
10 { comment: 'Great post!' },
11 { comment: "Can't wait to read more!" },
12 ],
13 },
14 },
15 },
16 })
17 const posts = await prisma.post.findMany({
18 include: {
19 comments: true,
20 },
21 })
22
23 console.dir(posts, { depth: Infinity })
24}
index.js
1async function main() {
2 await prisma.post.update({
3 where: {
4 slug: 'my-first-post',
5 },
6 data: {
7 comments: {
8 createMany: {
9 data: [
10 { comment: 'Great post!' },
11 { comment: "Can't wait to read more!" },
12 ],
13 },
14 },
15 },
16 })
17 const posts = await prisma.post.findMany({
18 include: {
19 comments: true,
20 },
21 })
22
23 console.dir(posts, { depth: Infinity })
24}

Now run the code using the same command as before:

$npx ts-node index.ts

Now run the code using the same command as before:

$node index.js

You will see the following output:

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

Fantastic, you just wrote new data into your database for the first time using Prisma Client 🚀

Edit this page on GitHub