Querying the database
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.
Create a new file named index.ts
and add the following code to it:
import { PrismaClient } from '@prisma/client'
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()
})
Here's a quick overview of the different parts of the code snippet:
- Import the
PrismaClient
constructor from the@prisma/client
node module - Instantiate
PrismaClient
- Define an
async
function namedmain
to send queries to the database - Connect to the database
- Call the
main
function - 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:
async function main() {
// ... you will write your Prisma Client queries here
+ const allUsers = await prisma.user.findMany()
+ console.log(allUsers)
}
Now run the code with this command:
npx ts-node index.ts
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:
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 })
}
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.author
↔ User.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
The output should look similar to this:
[
{
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',
},
],
},
]
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
tables:
User
id | name | |
---|---|---|
60cc9b0e001e3bfd00a6eddf | "hello@prisma.com" | "Rich" |
Post
id | createdAt | title | content | published | authorId |
---|---|---|---|---|---|
60cc9bad005059d6007f45dd | 2020-03-21T16:45:01.246Z | "My first post" | Lots of really interesting stuff | false | 60cc9b0e001e3bfd00a6eddf |
Note: The unique IDs in the
authorId
column onPost
reference theid
column of theUser
table, meaning theid
value60cc9b0e001e3bfd00a6eddf
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:
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 })
}
Now run the code using the same command as before:
npx ts-node index.ts
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 🚀