docs/1.25/prisma-client/basic-data-access/writing-data-JAVASCRIPT-rsc6.mdx
import Collapse from "components/Markdown/Collapse" import Code from "components/Markdown/Code" import Warning from "components/Markdown/Warning"
export const meta = { title: "Writing Data (JavaScript)", position: 60, technology: "node", technologyOrder: 1, articleGroup: "Writing Data", }
The Prisma client is based on the operations defined in the GraphQL schema of your Prisma API. For writing data, it basically mirrors the GraphQL mutations of your Prisma service.
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 new User record in the databaseupdateUser: Updates an existing User record in the databasedeleteUser: Deletes an existing User record from the databaseupsertUser: Updates an existing or create a new User record in the databaseupdateManyUsers: Updates many existing User records in the database at once.deleteManyUsers: Deletes many existing User 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.
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.
<Collapse title="View the types of the input object for `Link`, `User` and `Vote`">createLink herecreateUser herecreateVote hereCreate a new user:
<Code languages={["JavaScript", "GraphQL"]}>
const newUser = await prisma
.createUser({
name: "Alice",
email: "[email protected]",
password: "IlikeTurtles"
})
# generated mutation
mutation {
createUser(data: {
name: "Alice"
email: "[email protected]"
password: "IlikeTurtles"
}) {
id
name
email
password
}
}
Create a new vote:
<Code languages={["JavaScript", "GraphQL"]}>
const newVote = await prisma
.createVote({
user: {
connect: {
email: "[email protected]"
}
},
link: {
connect: {
id: "cjli47wr3005b0a23m9crhh0e"
}
}
})
# generated mutation
mutation {
createVote(data: {
user: {
connect: {
email: "[email protected]"
}
}
link: {
connect: {
id: "cjli47wr3005b0a23m9crhh0e"
}
}
}) {
id
}
}
Create a new user with two new links:
<Code languages={["JavaScript", "GraphQL"]}>
const newUserWithLinks = await prisma
.createUser({
name: "Alice",
email: "[email protected]",
password: "IlikeTurtles",
links: {
create: [{
description: "My first link",
url: "https://www.prisma.io"
}, {
description: "My second link",
url: "https://www.howtographql.com"
}]
},
})
# generated mutation
mutation {
createUser(data: {
name: "Alice"
email: "[email protected]"
password: "IlikeTurtles"
links: {
create: [{
description: "My first link",
url: "https://www.prisma.io"
}, {
description: "My second link",
url: "https://www.howtographql.com"
}]
}
}) {
id
name
email
password
}
}
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 a create-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.
Set a new name on an existing user:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedUser = await prisma
.updateUser({
data: {
name: "Alice"
},
where: {
id: "cjli512bd005g0a233s1ogbgy"
}
})
# generated mutation
mutation {
updateUser(
data: {
name: "Alice"
}
where: {
id: "cjli512bd005g0a233s1ogbgy"
}
) {
id
name
email
password
}
}
Update a link so that it was posted by a different user than before:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedLink = await prisma
.updateLink({
data: {
postedBy: {
connect: {
id: "cjli512bd005g0a233s1ogbgy"
}
},
},
where: {
id: "cjli47wr3005b0a23m9crhh0e"
}
})
mutation {
updateLink(
data: {
postedBy: {
connect: {
id: "cjli512bd005g0a233s1ogbgy"
}
}
}
where: {
id: "cjli47wr3005b0a23m9crhh0e"
}
) {
id
createdAt
description
url
}
}
Delete the user that made a vote:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedVote = await prisma
.updateVote({
data: {
user: {
delete: true
},
},
where: {
id: "cjli5aual005n0a233ekv89o4"
}
})
mutation {
updateVote(
data: {
user: {
delete: true
}
}
where: {
id: "cjli5aual005n0a233ekv89o4"
}
) {
id
}
}
For this operation to succeed, the
userfield on theVotemodel must not be required. Otherwise the constraint that everyVoteneeds to be connected to aUserwould be violated.
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.
deleteLink heredeleteUser heredeleteVote hereEach method call returns an object that contains all the scalar fields of the model that was just deleted.
Delete a link by its id:
<Code languages={["JavaScript", "GraphQL"]}>
const deletedLink = await prisma
.deleteLink({
id: "cjli47wr3005b0a23m9crhh0e"
})
mutation {
deleteLink(where: {
id: "cjli47wr3005b0a23m9crhh0e"
}) {
id
createdAt
description
url
}
}
Delete a user by their email:
<Code languages={["JavaScript", "GraphQL"]}>
const deletedUser = await prisma
.deleteUser({
email: "[email protected]"
})
mutation {
deleteUser(where: {
email: "[email protected]"
}) {
id
createdAt
description
url
}
}
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 the where field provided in update-methodsupdate: Identical to the data field provided in update-methodscreate: Identical to the input object provide in create-methodsUpdate the URL of a link. If the link doesn't exist yet, create a new one:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedOrCreatedLink = await prisma
.upsertLink({
where: {
id: "cjli47wr3005b0a23m9crhh0e"
},
update: {
url: "https://www.howtographql.com"
},
create: {
url: "https://www.howtographql.com",
description: "Fullstack GraphQL Tutorial"
}
})
mutation {
upsertLink(
where: {
id: "cjli47wr3005b0a23m9crhh0e"
}
update: {
url: "https://www.howtographql.com"
}
create: {
url: "https://www.howtographql.com"
description: "Fullstack GraphQL Tutorial"
}
) {
id
}
}
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.
Update three links, specified by their IDs, and reset their URLs to the empty string:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedLinksCount = await prisma
.updateManyLinks({
where: {
id_in: ["cjli6tknz005s0a23uf0lmlve", "cjli6tnkj005x0a2325ynfpb9", "cjli6tq3200620a23s4lp8npd"]
},
data: {
url: ""
},
}).count
mutation {
updateManyLinks({
where: {
id_in: ["cjli6tknz005s0a23uf0lmlve", "cjli6tnkj005x0a2325ynfpb9", "cjli6tq3200620a23s4lp8npd"]
}
data: {
url: ""
}
}) {
count
}
}
If one or more of the provided IDs do not actually exist in the database, the operation will not return an error.
</Warning>Update all links where the description contains the string graphql and reset their URLs to the empty string:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedLinksCount = await prisma
.updateManyLinks({
where: {
description_contains: "graphql"
},
data: {
url: ""
},
}).count
mutation {
updateManyLinks({
where: {
description_contains: "graphql"
}
data: {
url: ""
}
}) {
count
}
}
Delete all links that were created before 2018:
<Code languages={["JavaScript", "GraphQL"]}>
const deleteLinksCount = await prisma
.deleteManyLinks({
createdAt_lte: "2018"
}).count
mutation {
deleteManyLinks(where: {
createdAt_lte: "2018"
}) {
count
}
}
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.
The MongoDB database connector currently does not support ACID transactions. Learn more in this GitHub issue.
</Warning>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 model B and connects it via a relation field to the model A.update: Updates an existing model B that is connected to the model A via a relation field.upsert: Updates an existing model B that is connected to the model A via a relation field or creates a new model B and connects it via a relation field to the model A.delete: Deletes an existing model B that is connected to the model A via a relation field.connect: Connects an existing model B to an the model A via a relation field.disconnect: Disconnects an existing model B from the relation to model A.set: Connects an existing model B to an the model A via a relation field. If the model B was connected to a different model A before, it is further disconnected from that (the connection is "rewired").Create a new user with two new links and connect one existing link:
<Code languages={["JavaScript", "GraphQL"]}>
const newUserWithLinks = await prisma
.createUser({
name: "Alice",
email: "[email protected]",
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"
}
},
})
# generated mutation
mutation {
createUser(data: {
name: "Alice"
email: "[email protected]"
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"
}
}
}) {
id
name
email
password
}
}
Delete a link from a user:
<Code languages={["JavaScript", "GraphQL"]}>
const updatedUser = await prisma
.updateUser({
where: {
id: "cjli8znnd006n0a23ywc6wf8w"
},
data: {
links: {
delete: {
id: "cjli6tknz005s0a23uf0lmlve"
}
}
}
})
mutation {
updateUser(
where: {
id: "cjli8znnd006n0a23ywc6wf8w"
}
data: {
links: {
delete: {
id: "cjli6tknz005s0a23uf0lmlve"
}
}
}
) {
id
}
}