Report this

What is the reason for this report?

How to create update mutation in GraphQl

Posted on March 26, 2021

I followed your article on “How To Build a GraphQL Server in Node.js Using GraphQL-yoga and MongoDB”(https://www.digitalocean.com/community/tutorials/how-to-build-a-graphql-server-in-node-js-using-graphql-yoga-and-mongodb. It was explained very well I understand it nicely but can you please add how to create update mutation for the same. I will very thankful to you.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there,

Happy to hear that you found the article helpful. Let’s dive into how to add an update mutation to your GraphQL server built with graphql-yoga and MongoDB.

For the sake of context, let’s assume that the schema outlined in the original article is related to a Book type, and you want to be able to update a book’s details.

  1. Update your GraphQL Schema:

First, you’ll need to define the update mutation in your GraphQL schema:

type Mutation {
    ...
    updateBook(id: ID!, title: String, author: String): Book!
}

The mutation updateBook expects an id (which is mandatory) and can receive a new title and/or author (both optional). It returns the updated Book.

  1. Implement the Resolver:

In the resolver functions for your mutations, add the resolver for updateBook:

const Mutation = {
    ...
    updateBook: async (parent, args, context, info) => {
        const { id, ...update } = args;

        // Ensure some fields are provided for update
        if (!Object.keys(update).length) {
            throw new Error("You must provide at least one field for update.");
        }

        const updatedBook = await context.db.collection('books').findOneAndUpdate(
            { _id: ObjectId(id) },
            { $set: update },
            { returnOriginal: false }  // This ensures the updated document is returned
        );

        if (!updatedBook.value) {
            throw new Error(`Failed to update book with id ${id}.`);
        }

        return updatedBook.value;
    }
};

The ObjectId is a utility from the mongodb package to convert string IDs to MongoDB’s ObjectId format.

  1. Test the Update Mutation:

Using a GraphQL playground or a client, you can now test the update mutation:

mutation {
    updateBook(id: "some_book_id", title: "New Title") {
        id
        title
        author
    }
}

This mutation updates the book with the given id by setting a new title. The returned data includes the id, updated title, and the author of the book.

Best,

Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.