Writing Data (JavaScript)
Overview
The Prisma client is generated from your datamodel. Its API exposes CRUD and other operations for the models defined in the datamodel.
For this page, we'll assume your Prisma project is based on the following datamodel:
type Post {
id: ID! @id
createdAt: DateTime! @createdAt
updatedAt: DateTime! @updatedAt
title: String!
published: Boolean! @default(value: false)
author: User
comments: [Comment!]!
}
type User {
id: ID! @id
name: String
email: String! @unique
role: Role! @default(value: USER)
posts: [Post!]!
comments: [Comment!]!
}
type Comment {
id: ID! @id
createdAt: DateTime! @createdAt
text: String!
post: Post!
writtenBy: User!
}
enum Role {
USER
ADMIN
}
For each model type in your datamodel, six methods for writing data are generated. For example, for the User
model the following operations are available:
createUser
: Creates a newUser
record in the database.updateUser
: Updates an existingUser
record in the database.deleteUser
: Deletes an existingUser
record from the database.upsertUser
: Updates an existing or create a newUser
record in the database.updateManyUsers
: Updates many existingUser
records in the database at once.deleteManyUsers
: Deletes many existingUser
records from the database at once.
Creating records
When creating new records in the database, the create
-method takes one input object which wraps all the scalar fields of the record to be created. It also provides a way to create relational data for the model, this can be supplied using nested object writes.
Each method call returns a Promise for an object that contains all the scalar fields of the model that was just created.
Examples
Create a new user:
const newUser = await prisma.createUser({ name: 'Alice', email: 'alice@prisma.io', })
Copy
Create a new post and set alice@prisma.io
as the author:
When using the MySQL or Postgres databases connectors, the following call is executed as a single database transaction. The MongoDB connector doesn't support transactions yet. Learn more in the Declarative nest writes section.
const post = prisma.createPost({ title: 'Join us for GraphQL Conf in 2019', author: { connect: { email: 'alice@prisma.io' }, }, })
Copy
Create a new user with two new posts:
When using the MySQL or Postgres databases connectors, the following call is executed as a single database transaction. The MongoDB connector doesn't support transactions yet.
const newUser = await prisma.createUser({ name: 'Alice', email: 'alice@prisma.io', posts: { create: [ { title: 'Follow Prisma on Twitter', }, { title: 'Join us for GraphQL Conf in 2019', }, ], }, })
Copy
Updating records
When updating existing records in the database, the update
-method receives one input object with two fields:
data
: This is similar to the input object you provide to acreate
-method. It wraps scalar fields of the model to be updated and lets you provide relational data via nested object writes.where
: This is used to select the record that should be updated. You can use any unique field to identify the record. For the example datamodel above, this means that forUser
,Post
andComment
it has anid
property. ForUser
it additionally accepts theemail
field.
Each method call returns a Promise for an object that contains all the scalar fields of the model that was just updated.
Examples
Update the role of an existing user:
const updatedUser = await prisma.updateUser({ data: { role: 'ADMIN', }, where: { id: 'cjli512bd005g0a233s1ogbgy', }, })
Copy
Update the author of a post:
const updatedPost = await prisma.updatePost({ data: { author: { connect: { email: 'bob@prisma.io' }, }, }, where: { id: 'cjli47wr3005b0a23m9crhh0e' }, })
Copy
Deleting records
When deleting records from the database, the delete
-method receives one input object that specifies which record is to be deleted. The type of this input object is identical to the where
object in update
-methods.
The properties of that object correspond to those fields of the model that are marked as unique. For the example datamodel above, this means that for User
, Post
and Comment
it has an id
property. For User
it additionally accepts the email
field.
Each method call returns a Promise for object that contains all the scalar fields of the model that was just deleted.
Examples
Delete a post by its id:
const deletedPost = await prisma.deletePost({ id: 'cjli47wr3005b0a23m9crhh0e', })
Copy
Delete a user by their email:
const deletedUser = await prisma.deleteUser({ email: 'alice@prisma.io', })
Copy
Creating or updating objects (upserts)
Upsert operations allow you to try to update an existing record. If that record actually does not exist yet, it will be created. The upsert
-methods are a mix of create
- and update
-methods, meaning they receive an input argument that has three fields:
where
: Identical to thewhere
field provided inupdate
-methodsupdate
: Identical to thedata
field provided inupdate
-methodscreate
: Identical to the input object provide increate
-methods
Examples
Update the role of a user. If the user doesn't exist yet, create a new one:
const updatedOrCreatedUser = await prisma.upsertUser({ where: { email: 'alice@prisma.io', }, update: { role: 'ADMIN', }, create: { name: 'Alice', email: 'alice@prisma.io', role: 'ADMIN', }, })
Copy
Updating and deleting many records in bulk
The Prisma client API offers special methods to update or delete many records at once. Each updateMany
- and deleteMany
-method returns the number of records that ultimately have been affected by the operation.
Examples
Unpublish three posts by their IDs:
const updatedPostCount = await prisma .updateManyPosts({ where: { id_in: [ 'cjsviilio0g8f0b430jbnyvi7', 'cjli6tnkj005x0a2325ynfpb9', 'cjli6tq3200620a23s4lp8npd', ], }, data: { published: false }, }) .count()
Copy
If one of more of the provided IDs does not actually exist in the database, the operation will not return an error. The returned count
indicates how many records actually were updated.
Update all posts where the description contains the string prisma
and publish them:
const updatedPostsCount = await prisma .updateManyPosts({ where: { title_contains: 'prisma' }, data: { published: true }, }) .count()
Copy
Delete all posts that were created before 2018:
const deletePostCount = await prisma .deleteManyPost({ createdAt_lte: '2018', }) .count()
Copy
Nested object writes
Nested object writes let you modify multiple database records across relations in a single transaction. Nested object writes are available for create
- and update
-methods.
Because the model User
has a relation to Post
via the author
field, you can create/update/delete Post
records through createUser
and updateUser
operations. In these cases, the author
field in the data
object for createUser
and updateUser
operations can contain one or more of the following keywords:
create
: Creates a newPost
record and connects it via theauthor
field to theUser
record.update
: Updates aPost
record that is connected to aUser
record via theauthor
field.upsert
: Updates aPost
record that is connected to aUser
record via theauthor
field or creates a newPost
record and connects it via theauthor
field to theUser
record.delete
: Deletes aPost
record that is connected to aUser
record via theauthor
field.connect
: Connects aPost
record to aUser
record via theauthor
field.disconnect
: Disconnects aPost
record from aUser
record.set
: Connects aPost
record to aUser
record via theauthor
field. If thePost
record was connected to a differentUser
record before, it is disconnected from that one (set
effecitvely executesconnect
anddisconnect
operations under the hood).
Examples
Create a new user with two new posts and connect one existing post:
const newUser = await prisma.createUser({ name: 'Bob', email: 'bob@prisma.io', posts: { create: [ { title: 'Follow Prisma on Twitter', }, { title: 'Join us for GraphQL Conf in 2019', }, ], connect: { id: 'cjsviiljo0g9h0b43i943n4ni' }, }, })
Copy
Delete a comment of a user:
const updatedUser = await prisma.updateUser({ where: { id: 'cjli8znnd006n0a23ywc6wf8w' }, data: { comments: { delete: { id: 'cjli6tknz005s0a23uf0lmlve' }, }, }, })
Copy