Updating Data

Now that we know how to create and read data, it's time to explore updating the data we have saved. Grafbase automatically generates the update mutation for your types tagged with @model
.
So far we've used the actual values directly inside of our queries and mutations. We will now use GraphQL variables to benefit from greater type-safety.
Similar to how we can read data by fetching by id or unique field, we can do the same for updating data.
First let's explore updating an existing Post
by id
. We'll use GraphQL variables which you can pass inside of the Playground.
We'll begin by naming the operation UpdatePostById
then in inside of arguments we'll pass the variables $id
and $newTitle
. These variable names don't need to match the name of the fields, but you must provide the type that matches the schema.
You can then use those variables directly inside of the mutation
inside of the input
argument. We'll also fetch title
in the response.
mutation UpdatePostById($id: ID!, $newTitle: String!) {
postUpdate(by: { id: $id }, input: { title: $newTitle }) {
post {
title
}
}
}
The variables are a JSON object that must match the variable names you provided in the operation:
{
"id": "post_01GQ7YSZCB4ENYZVGBTBQFS4XE",
"newTitle": "Grafbase!"
}
Then the response will contain the requested field(s) — title
in our example:
{
"data": {
"postUpdate": {
"post": {
"title": "Grafbase!"
}
}
}
}
Just like we can update a Post
by id
, we can also update by a unique field.
We'll update the Post
by the unique field url
we defined in our schema previously. You'll notice here we are using the scalar URL
for the variable $url
:
mutation UpdatePostById($url: URL!, $newTitle: String!) {
postUpdate(by: { url: $url }, input: { title: $newTitle }) {
post {
title
}
}
}
Just like we did before we can pass the variables along with the request:
{
"url": "https://grafbase.com",
"newTitle": "Grafbase"
}