By DwijVirani
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!
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.
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.
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.
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
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.