Mutations: Creating, Updating, and Deleting Data

Learn GraphQL mutations, organize arguments with input types, and implement create, update, and delete operations.

🎯 Introduction

So far, our API only reads data. Real applications also need write operations, such as registering accounts, editing profiles, and deleting records. In GraphQL, these are handled by mutations.

By the end of this article, you will understand the roles of queries and mutations, organize complex arguments using input types, and implement complete create, update, and delete operations for user data.


🧱 What Is a Mutation?

A mutation is a GraphQL operation type for modifying data, alongside queries. Their responsibilities are clear:

  • Query: reads data without changing it, regardless of how often it runs, much like REST's GET.
  • Mutation: changes data, covering the work done by POST, PUT, and DELETE in REST.

The syntax is nearly identical; replace the outer query keyword with mutation:

mutation {
    createUser(input: { username: "Sam", age: 25 }) {
        id
        username
    }
}

Mutations that return objects also require a selection of return fields. After a create or update operation, the server returns the latest values of those fields, saving the client another query to refresh them.

This division is a convention that resolver code must follow. It is technically possible to modify data inside a query resolver, but clients and caching tools assume queries have no side effects. Breaking that assumption can cause problems that are difficult to debug.

🛠 Input Types

Creating a user involves several fields. Listing each one as an argument makes declarations increasingly long:

# Many separate arguments become difficult to maintain
type Mutation {
    createUser(username: String!, age: Int, city: String): User!
}

GraphQL provides input types to group these arguments into an input object.

input CreateUserInput {
    username: String!
    age: Int
    city: String
}

type Mutation {
    createUser(input: CreateUserInput!): User!
}

input and type look similar, but input defines input objects, while type defines output objects. They cannot be used interchangeably. This offers two benefits:

  • The input structure is managed in one place, so adding or removing fields requires a single change.
  • Variables keep calls tidy: pass the input as one JSON object:
{
    "input": {
        "username": "Sam",
        "age": 25
    }
}
mutation Create($input: CreateUserInput!) {
    createUser(input: $input) {
        id
        username
    }
}

✨ Implementing Create, Update, and Delete

Let's implement all three operations. Start with the schema:

input CreateUserInput {
    username: String!
    age: Int
    city: String
}

input UpdateUserInput {
    username: String
    age: Int
    city: String
}

type Mutation {
    createUser(input: CreateUserInput!): User!
    updateUser(id: ID!, input: UpdateUserInput!): User
    deleteUser(id: ID!): Boolean!
}

Notice these design choices:

  • Every field in UpdateUserInput is nullable: supply only the fields to change; omitted fields remain untouched.
  • updateUser returns nullable User: when no matching user exists, it returns null, allowing the client to show a user-not-found message.
  • deleteUser returns Boolean!: true or false explicitly indicates whether deletion succeeded.

Now the resolvers:

server.js
const resolvers = {
    Mutation: {
        createUser: (parent, args) => {
            const user = {
                id: String(users.length + 1),
                ...args.input,
            };
            users.push(user);
            return user;
        },
        updateUser: (parent, args) => {
            const user = users.find((item) => item.id === args.id);
            if (!user) {
                return null;
            }
            Object.assign(user, args.input);
            return user;
        },
        deleteUser: (parent, args) => {
            const index = users.findIndex((item) => item.id === args.id);
            if (index === -1) {
                return false;
            }
            users.splice(index, 1);
            return true;
        },
    },
};

These are familiar array operations: push creates an entry, Object.assign merges updates, and splice removes an entry. Once a resolver receives args.input, writing data is ordinary Node.js code.

Start the server and try these operations in Sandbox in order:

mutation {
    updateUser(id: "1", input: { age: 21 }) {
        username
        age
    }
}
mutation {
    deleteUser(id: "2")
}
The data lives in an in-memory array, so all changes are lost when the server restarts. This keeps learning simple. In a real application, replace the array operations in resolvers with database operations; the schema and client queries can remain unchanged.

💡 Multiple Fields in One Mutation

As with queries, a single mutation request can include multiple fields, distinguished with aliases:

mutation {
    a: createUser(input: { username: "James" }) {
        id
    }
    b: createUser(input: { username: "Oliver" }) {
        id
    }
}

An important execution rule applies: top-level mutation fields execute serially, one after another, while query fields can execute in parallel. This keeps writes in a predictable order, such as creating an entry before updating it.


❓ Questions and Answers

Q1: Why not use REST for create, update, and delete operations?

GraphQL uses one endpoint and a consistent syntax for reads and writes. Clients do not need to track multiple URLs and HTTP methods, and can select return fields. This is a design choice; neither approach is universally better.

Q2: Can input types contain other input types?

Yes. For example, CreateArticleInput can contain a field of type CreateAuthorInput. Prefer flatter structures where practical, since deeply nested inputs can be harder for callers to maintain.

Q3: What happens to a user's articles when the user is deleted?

That is a business decision. You might delete the articles too, or retain them and mark the author as deleted. GraphQL does not decide this; implement the required behavior in resolvers.

Q4: How do I clear a field during an update?

Pass null, as in input: { city: null }. Object.assign overwrites the value with null. Omitting a field and passing null are different: omission leaves it unchanged, while null clears it.

Q5: Can a mutation read data?

Yes. Resolvers are ordinary functions that can both write and read data. Returning the updated object combines a write with a read.


🧪 Exercises

Exercise 1: Implement createArticle(input: CreateArticleInput!): Article!, with title and authorId in the input. Return the new article's ID and title.

# Write your code here

Exercise 2: Implement updateArticle(id: ID!, input: UpdateArticleInput!): Article. Return null if no article is found, and test both cases in Sandbox.

const resolvers = {
    Mutation: {
        // Write your code here
    },
};

🎉 You can now create, update, and delete data with GraphQL! The service still runs independently. Next, we will integrate it with Express so it can coexist with REST endpoints in the same project.