Writing Data (TypeScript)
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 API is based on the following datamodel:
type Link {
id: ID! @unique
createdAt: DateTime!
description: String!
url: String!
postedBy: User
votes: [Vote!]!
}
type User {
id: ID! @unique
name: String!
email: String! @unique
password: String!
links: [Link!]!
votes: [Vote!]!
}
type Vote {
id: ID! @unique
link: Link!
user: User!
}
For each model type in your datamodel, six methods for writing data are generated. These are named after the mutations in the GraphQL schema, e.g. for the User
model:
createUser
: Creates a newUser
record in the databaseupdateUser
: Updates an existingUser
record in the databasedeleteUser
: Deletes an existingUser
record from the databaseupsertUser
: Updates an existing or create a newUser
record in the databaseupdateManyUsers
: Updates many existingUser
records in the database at once.deleteManyUsers
: Deletes many existingUser
records from the database at once.
Each invokation of one of these methods is executed as a transaction, meaning it is either guaranteed to succeed entirely or be rolled back if it partially fails.
Creating objects
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 an object that contains all the scalar fields of the model that was just created.
Examples
Create a new user:
const newUser: UserNode = await prisma.createUser({ name: 'Alice', email: 'alice@prisma.io', password: 'IlikeTurtles', })
Copy
Create a new vote:
const newVote: VoteNode = await prisma.createVote({ user: { connect: { email: 'alice@prisma.io', }, }, link: { connect: { id: 'cjli47wr3005b0a23m9crhh0e', }, }, })
Copy
Create a new user with two new links:
const newUserWithLinks: UserNode = await prisma.createUser({ name: 'Alice', email: 'alice@prisma.io', password: 'IlikeTurtles', links: { create: [ { description: 'My first link', url: 'https://www.prisma.io', }, { description: 'My second link', url: 'https://www.howtographql.com', }, ], }, })
Copy
Updating objects
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.
data
where
Each method call returns an object that contains all the scalar fields of the model that was just updated.
Examples
Set a new name on an existing user:
const updatedUser: UserNode = await prisma.updateUser({ data: { name: 'Alice', }, where: { id: 'cjli512bd005g0a233s1ogbgy', }, })
Copy
Update a link so that it was posted by a different user than before:
const updatedLink: LinkNode = await prisma.updateLink({ data: { postedBy: { connect: { id: 'cjli512bd005g0a233s1ogbgy', }, }, }, where: { id: 'cjli47wr3005b0a23m9crhh0e', }, })
Copy
Delete the user that made a vote:
const updatedVote: VoteNode = await prisma.updateVote({ data: { user: { delete: true, }, }, where: { id: 'cjli5aual005n0a233ekv89o4', }, })
Copy
For this operation to succeed, the
user
field on theVote
model must not be required. Otherwise the constraint that everyVote
needs to be connected to aUser
would be violated.
Deleting objects
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
, Vote
and Link
it has an id
property. For User
it additionally accepts the email
field.
Each method call returns an object that contains all the scalar fields of the model that was just deleted.
Examples
Delete a link by its id:
const deletedLink: LinkNode = await prisma.deleteLink({ id: 'cjli47wr3005b0a23m9crhh0e', })
Copy
Delete a user by their email:
const deletedUser: UserNode = 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 URL of a link. If the link doesn't exist yet, create a new one:
const updatedOrCreatedLink: LinkNode = await prisma.upsertLink({ where: { id: 'cjli47wr3005b0a23m9crhh0e', }, update: { url: 'https://www.howtographql.com', }, create: { url: 'https://www.howtographql.com', description: 'Fullstack GraphQL Tutorial', }, })
Copy
Updating and deleting many records
The Prisma client API offers special methods to update or delete many records at once. The corresponding mutations in the generated GraphQL API of your Prisma service are called batch mutations. Each updateMany
- and deleteMany
-method only returns the number of records that ultimately have been affected by the operation.
Examples
Update three links, specified by their IDs, and reset their URLs to the empty string:
const updatedLinksCount: number = await prisma.updateManyLinks({ where: { id_in: [ 'cjli6tknz005s0a23uf0lmlve', 'cjli6tnkj005x0a2325ynfpb9', 'cjli6tq3200620a23s4lp8npd', ], }, data: { url: '', }, }).count
Copy
If one of more of the provided IDs does not actually exist in the database, the operation will not return an error.
Update all links where the description contains the string graphql
and reset their URLs to the empty string:
const updatedLinksCount: number = await prisma.updateManyLinks({ where: { description_contains: 'graphql', }, data: { url: '', }, }).count
Copy
Delete all links that were created before 2018:
const deleteLinksCount: number = await prisma.deleteManyLinks({ createdAt_lte: '2018', }).count
Copy
Nested object writes
Nested object writes let you modify database records across multiple models in a single transaction. The corresponding concept from Prisma GraphQL API is called nested mutations. Nested object writes are available for create
- and update
-methods.
If a model A
has a relation to a different model B
, you can write to the model B
through createA
and updateA
operations. In these cases, the data
argument for the createA
and updateA
operations can contain one of the following keywords:
create
: Creates a new modelB
and connects it via a relation field to the modelA
.update
: Updates an existing modelB
that is connected to the modelA
via a relation field.upsert
: Updates an existing modelB
that is connected to the modelA
via a relation field or creates a new modelB
and connects it via a relation field to the modelA
.delete
: Deletes an existing modelB
that is connected to the modelA
via a relation field.connect
: Connects an existing modelB
to an the modelA
via a relation field.disconnect
: Disconnects an existing modelB
from the relation to modelA
.set
: Connects an existing modelB
to an the modelA
via a relation field. If the modelB
was connected to a different modelA
before, it is further disconnected from that (the connection is "rewired").
Examples
Create a new user with two new links and connect one existing link:
const newUserWithLinks: UserNode = await prisma.createUser({ name: 'Alice', email: 'alice@prisma.io', password: 'IlikeTurtles', links: { create: [ { description: 'My first link', url: 'https://www.prisma.io', }, { description: 'My second link', url: 'https://www.howtographql.com', }, ], connect: { id: 'cjli6tknz005s0a23uf0lmlve', }, }, })
Copy
Delete a link from a user:
const updatedUser: UserNode = await prisma.updateUser({ where: { id: 'cjli8znnd006n0a23ywc6wf8w', }, data: { links: { delete: { id: 'cjli6tknz005s0a23uf0lmlve', }, }, }, })
Copy