Create an entry in the database with Prisma Client

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 2 years ago
Updated a year ago

In this lesson, we will write a code snippet which creates a new entry in the database. We will import and use the Prisma Client that we previously generated by running the command npx prisma generate to perform this query.

Thanks to type-safety, we can now directly catch mismatched data field types while we are coding, drastically reducing the chance of having bugs in the code.

Tip - When in doubt, you can always use the key combination ctrl-space to invoke the autocomplete feature of VS Code. This is also a huge benefit made possible by Prisma's type-safety, and is super handy for exploring the Prisma Client API.

Xiaoru Li: [0:00] Let's create a new sample.ts file to perform some basic database queries with Prisma Client. The first thing we'll need to do is to import { PrismaClient } from '@prisma/client' package, which is automatically installed for us when we ran the prisma generate command previously.

[0:21] Then, we'll instantiate a new PrismaClient. Now we can use this Prisma object to read and write data in our database. If we type prisma., we can see VS Code automatically gives us the profile suggestion, along with some generated documentation, which is based on the profile data model that we've predefined in our schema.prisma file.

[0:47] If we select the profile from here, we'll then get a list of operations now we can perform on this model in a database. Let's try to create a new profile entry.

[0:59] The create method takes in an object as an argument, and if we hit Ctrl+Space in VS Code, all the possible fields will be shown. We'll use data to create an entry, which is going to be an object with a name property, let's call it "Sam."

[1:18] This whole query is an asynchronous function call that will return the entry that we created in the database, and because top-level awaits doesn't make sense, we'll wrap all the code inside an async function called main(). We'll also disconnect Prisma Client after this operation is finished.

[1:43] Now, if we run our code with tiers node, let's see the entry logs in the console. Notice that if we use a number instead of a string for the name field, we'll get a TypeError, because everything in Prisma Client is automatically generated based on our schema file and is always type safe.