Latest posts

Use the arrows beside each title, or press J and K, to move between posts.

A hand turns a glowing key in the lock of a chained vault door, beside a sealed scroll labelled JSON Web Token

In Part 3 we moved our Hammer collection into MongoDB, so our changes finally survive a restart. But there is a problem. Anyone who can reach the server can add films, mark them as watched, or delete the lot. Our archive has no lock on the door.

In this post we’ll build the authentication layer. To do this right in 2026, we’ll use JWTs (JSON Web Tokens). This allows your server to stay "stateless": it doesn't have to remember every logged-in user, it just has to trust the "digital seal" (the token) they carry.

We need to add four things:

  • A User Model: To store credentials (with hashed passwords, never store plain text!).
  • Auth Mutations: signup and login operations that return a token.
  • The Context Hook: A way for Apollo to check for a token before every request.
  • Guards: Checks in our resolvers so only logged-in users can change the archive, and only an admin can delete from it.

We’ll build on the code from Part 3, adding two new packages: jsonwebtoken creates and checks the tokens, and bcryptjs hashes passwords. If you’re following along in your Part 3 folder, install them now:

bash
cd lab/graphql-tutorial-3
npm install jsonwebtoken bcryptjs

If you’d rather jump straight to the finished code, it’s in the graphql-tutorial-4 folder of the lab repository:

bash
git clone https://github.com/jmwollny/lab.git
cd lab/graphql-tutorial-4
npm install

The User Model

First, we need a way to store users. Create models/User.js next to Film.js:

javascript
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  role: { type: String, enum: ['HUNTER', 'ADMIN'], default: 'HUNTER' }
});

// Hash the password before it is saved, so it is never stored as plain text
userSchema.pre('save', async function () {
  if (!this.isModified('password')) return;
  this.password = await bcrypt.hash(this.password, 10);
});

module.exports = mongoose.model('User', userSchema);

Every new user is a HUNTER. The ADMIN role is for the trusted few, and we’ll use it later to decide who is allowed to destroy films.

The pre('save') hook runs just before a user is written to the database and swaps the password for a bcrypt hash. The 10 is the cost factor: how much work it takes to compute the hash. Higher is slower for an attacker trying to guess passwords, but also slower for your server.

Creating and Checking Tokens

Both the login code and the request check need the same secret, so let's keep everything to do with tokens in one place. Create auth.js:

javascript
const jwt = require('jsonwebtoken');

// In production, set JWT_SECRET as an environment variable. The fallback is for local development only.
const SECRET = process.env.JWT_SECRET || 'VAN_HELSING_SECRET';

// Seal the user's id and role into a token that expires after 7 days
const createToken = (user) =>
  jwt.sign({ userId: user.id, role: user.role }, SECRET, { expiresIn: '7d' });

// Read the user from an "Authorization: Bearer <token>" header. Returns null if there is no valid token.
const getUser = (header = '') => {
  const token = header.replace('Bearer ', '');
  if (!token) return null;
  try {
    return jwt.verify(token, SECRET);
  } catch {
    return null; // expired, or tampered with
  }
};

module.exports = { createToken, getUser };

jwt.sign packs the user's id and role into the token and signs it with the secret. jwt.verify checks that signature. If anyone edits the token (say, changing their role to ADMIN) or it has expired, verification fails and we treat the request as anonymous.

Keep the secret secret. Anyone who knows it can forge a token for any user.

Update the Type Definitions

Now for the schema. In index.js, add a User type, an AuthPayload type for what signup and login return, and the two new mutations:

graphql
type User {
  id: ID!
  username: String!
  role: String!
}

type AuthPayload {
  token: String!
  user: User!
}

type Mutation {
  # ... existing mutations ...

  # Create an account and get a token
  signup(username: String!, password: String!): AuthPayload

  # Swap a username and password for a token
  login(username: String!, password: String!): AuthPayload
}

Notice that the User type has no password field. The hash lives in MongoDB, but because it isn't in the schema, GraphQL can never send it to a client.

Implement the Resolvers

This is where the heavy lifting happens: checking passwords and signing tokens. At the top of index.js, pull in Apollo's error classes along with the new modules:

javascript
const { ApolloServer, gql, AuthenticationError, ForbiddenError, UserInputError } = require('apollo-server');
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const FilmModel = require('./models/Film');
const User = require('./models/User');
const { createToken, getUser } = require('./auth');

Then add signup and login to the Mutation resolvers:

javascript
Mutation: {
  // SIGNUP: create a user and return a token
  signup: async (parent, { username, password }) => {
    if (await User.exists({ username })) {
      throw new UserInputError('That username is already taken');
    }
    const user = await User.create({ username, password });
    return { token: createToken(user), user };
  },

  // LOGIN: check the credentials and return a token
  login: async (parent, { username, password }) => {
    const user = await User.findOne({ username });
    const valid = user && (await bcrypt.compare(password, user.password));
    if (!valid) {
      throw new AuthenticationError('Invalid username or password');
    }
    return { token: createToken(user), user };
  },

  // ... your existing addFilm, updateWatched and deleteFilm ...
}

bcrypt.compare hashes the password the user typed and checks it against the stored hash. We never need to turn the hash back into the password (and we can't).

Login gives the same error whether the username doesn't exist or the password is wrong. That's deliberate: a different message for each would tell an attacker which usernames are real.

The Context Hook

Next, we change how the server starts. We want to peek at the Authorization header on every request:

javascript
const server = new ApolloServer({
  typeDefs,
  resolvers,
  // Runs before every request: whatever it returns is the third argument of every resolver
  context: ({ req }) => ({ user: getUser(req.headers.authorization) }),
});

With a valid token, context.user holds the token's contents (userId and role). Without one, it's null. Queries don't look at it, so anyone can still browse the archive.

Protecting the Resolvers

Now let's make sure only a logged-in user can change the archive. Add two small guards above the resolvers:

javascript
const requireUser = (context) => {
  if (!context.user) {
    throw new AuthenticationError('You must be a registered Hunter to modify the archive!');
  }
  return context.user;
};

const requireAdmin = (context) => {
  if (requireUser(context).role !== 'ADMIN') {
    throw new ForbiddenError('Only an Admin can destroy a film');
  }
};

Then call them at the start of each mutation. Resolvers receive the context as their third argument, so add context to each one:

javascript
addFilm: async (parent, { input }, context) => {
  requireUser(context);
  const newFilm = new FilmModel(input);
  return await newFilm.save();
},

updateWatched: async (parent, { id, watched }, context) => {
  requireUser(context);
  // ... the rest is unchanged from Part 3
},

deleteFilm: async (parent, { id }, context) => {
  requireAdmin(context);
  // ... the rest is unchanged from Part 3
},

Any registered Hunter can add films and track what they've watched, but only an Admin can destroy a film.

The two error classes do more than set a message. Apollo adds a code to the error (UNAUTHENTICATED or FORBIDDEN), so a frontend can tell "please log in" apart from "you're not allowed to do that" without matching on the text.

Testing the Flow in the Sandbox

Restart your server with node index.js and open http://localhost:4000/. Then follow this sequence.

1. Try a protected mutation without a token. It should be refused:

graphql
mutation {
  addFilm(input: { title: "The Abominable Snowman", year: 1957, watched: false }) {
    id
    title
  }
}
json
{
  "errors": [
    {
      "message": "You must be a registered Hunter to modify the archive!",
      "path": ["addFilm"],
      "extensions": {
        "code": "UNAUTHENTICATED"
      }
    }
  ],
  "data": {
    "addFilm": null
  }
}

2. Sign up:

graphql
mutation {
  signup(username: "VanHelsing", password: "garlic-and-stakes") {
    token
    user {
      username
      role
    }
  }
}

3. Copy the token. You’ll get a long string back, starting eyJ.

4. Set the Authorization header. In the Apollo Sandbox, open the Headers tab at the bottom and add:

  • Key: Authorization
  • Value: Bearer YOUR_TOKEN_HERE

5. Run the addFilm mutation again. This time the context function verifies the token and lets you through. Marking a film as watched with updateWatched works too.

6. Try to delete the film. You'll get a FORBIDDEN error, because VanHelsing is only a HUNTER. To promote him, open the Mongo shell:

bash
mongosh hammer_films --eval 'db.users.updateOne({ username: "VanHelsing" }, { $set: { role: "ADMIN" } })'

Run deleteFilm again and it is still forbidden. The role is sealed inside the token, and that token was issued when VanHelsing was a mere Hunter. Run the login mutation, put the new token in the header, and the delete goes through.

That last step shows the trade-off of tokens. The server trusts what the token says until it expires, so changes to a user's role (or a ban) only take effect at their next login. That's why we gave our tokens a 7-day expiry rather than letting them live forever.

Why Stateless?

By using this method, your server doesn't have a "session" it needs to keep track of in memory. The token itself contains the user's ID and role. If your server crashes and restarts, the user stays logged in because the token is still valid. And if you run several copies of the server, any of them can check the token, because all they need is the secret.

Conclusion

We began this journey with nothing but a local array and a list of Hammer films. Over the course of this series, we’ve transformed that humble start into a GraphQL/MongoDB ecosystem.

What We’ve Built

  • The Blueprint (Part 1): We defined our schema and learned how to query data with the precision of a surgeon.
  • The Mutation (Part 2): We moved beyond "Read-Only" and gave our API the power to create, update, and delete records.
  • The Immortal Vault (Part 3): We integrated MongoDB, ensuring our data survives a server restart and scales as our collection grows.
  • The Gatekeeper (Part 4): We secured the archive with JWT Authentication and bcrypt hashing, with roles deciding who can do what.

What’s Next for You?

Suggestions to try.

  1. Deployment: Take your API out of localhost and host it on a platform like Railway or Render. Remember to set JWT_SECRET there rather than relying on the fallback.
  2. Frontend Integration: Build a React or Next.js dashboard to visualize your "Watched" list, with a login form that stores the token and sends it with each request.
  3. Per-user Watch Lists: At the moment, "watched" is shared by everyone. Try storing it against each user instead, so every Hunter keeps their own list.
  4. Advanced Filtering: Use MongoDB's aggregation pipelines to find the most prolific directors or actors in your archive.

Happy coding!

Comments and sharing

Introduction

This article will explore the different ways to maintain "state"—the memory of your React application.

Choosing the right state management approach can be the difference between a clean, scalable app and a "prop-drilling" nightmare. This guide will compare the four most common approaches: useState, useReducer, Context API, and External Stores.


Managing State – Do’s and Do Not’s

When architecting your React app, follow these best practices to keep your data flow predictable.

  • DO keep state as local as possible. If only one component needs it, use useState.
  • DO use useReducer when one state change affects multiple sub-values (like a form) or when the state value is a result of complex logic or calculations.
  • DON'T put everything in a global store; it makes debugging harder and can slow down performance.
  • DO lift state up to the nearest common ancestor when two sibling components need the same data.
  • DO return a new object in your Reducer rather than mutating the old one.
MethodBest For...ComplexityScaling
useStateLocal UI toggle, simple inputsLowLimited
useReducerComplex logic, related state piecesMediumMedium
Context APITheming, User Auth, LanguageMediumMedium
ExternalComplex data, high-frequency updatesHighExcellent

Defining the Scenarios

Our comparison focuses on four specific use cases. This post highlights the implementation of the first three, with a deep dive into external stores coming in a later post.

  1. Local State: Managing a simple toggle or text input.
  2. Complex Local State: Managing a character's stats (Health, Mana, XP) in a game.
  3. Shared State: Passing a "Dark Mode" setting across the entire app.
  4. Complex Global State: Managing a shopping cart with persistent storage.

Implementation Guide

1. Local State with useState

Most of your state should live here. It’s fast, simple, and built into React.

JavaScript

javascript
import React, { useState } from 'react';

function Counter() {
  // Define a state variable called "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

2. The "Mission Control" with useReducer

When your state logic gets hairy—like a game character with multiple stats—useReducer is your best friend. It separates the "what happened" (Action) from the "how to update" (Reducer).

JavaScript

javascript
// The Reducer function handles all the logic outside the component, in one place
function reducer(state, action) {
  switch (action.type) {
    case 'attacked': return { ...state, hp: state.hp - 10 };
    case 'heal': return { ...state, hp: state.hp + 10 };
    default: return state;
  }
}

const [state, dispatch] = useReducer(reducer, { hp: 100 });

// Trigger it anywhere
dispatch({ type: 'attacked' });

Pros: Centralized logic, easier to test, great for complex objects.

Cons: More boilerplate code than a simple useState.

3. Global Strategy with Context API

When you need to share data without passing props manually through every level, use Context.

JavaScript

javascript
const ThemeContext = React.createContext('light');
// ... wrap your app in <ThemeContext.Provider>
const theme = useContext(ThemeContext);

Pros: Included in React, avoids prop-drilling.

Cons: Can cause unnecessary re-renders if not managed carefully.


Which one should you use?

Open your code editor and look at your component tree.

  • If the data is a single value: useState.
  • If the data is an object with related properties: useReducer.
  • If the data is "Global" (User info, Theme): Context API.
  • If the data is massive and changes constantly: Zustand or Redux.

The result of picking the right tool might not look "exciting" in the code itself, but your future self—who has to debug this in six months—will definitely give you a pat on the back!

Alternative state management frameworks such as Redux will be addressed in a future post. Keep your eyes peeled!

Comments and sharing

If there is one thing I have learnt during my career in the IT industry, it's that the industry is a fickle beast. Trends and fashions come and go. Languages fall by the wayside(hey COBOL74!). How often have you read an article declaring a new framework a "game changer", only to realise that after using it in anger it does a fraction of what a venerable equivalent does in it's sleep?

In this article I'm going to cover something that has not changed and has not gone out of fashion. It crops up again and again.

If there's one thing you need to learn and more importantly USE, as a software engineer it is encapulated(see what I did there?) in these 5 principles. But hey, enough of my yakkin', whaddaya say? Let's boogie!

The SOLID principles are a set of five design guidelines in object-oriented software development that help engineers create systems that are easy to maintain, scale, and understand. Introduced by Robert C. Martin, these principles aim to reduce "code rot" and make software more robust.


1. Single Responsibility Principle (SRP)

"A class should have one, and only one, reason to change."

This principle states that a component should perform a single function. When a class handles multiple unrelated tasks, it becomes fragile. A change in one task might accidentally break another. You might be tempted to add a small related function, but don't do it. Do what is right and create a new class even if it has one function. Smaller classes are great. Less dependencies, easier to test. What's not to like?

  • Example: Imagine a User class that handles both user data and saving that data to a database. If you change your database schema, you have to modify the User class.
  • Better Approach: Create a User class for data and a UserRepository class for database operations.

2. Open/Closed Principle (OCP)

"Software entities should be open for extension, but closed for modification."

This somewhat opaquely named principle states that you should be able to add new functionality to a system without changing existing code. This prevents bugs from being introduced into parts of the application that are already working. It comes down to my tenet of minimal code change. Remember every code change has possibility to introduce bugs!

  • Example: A Discount class that uses a series of if/else statements to check for "VIP" or "Seasonal" discounts. Adding a new discount type requires changing the existing logic.
  • Better Approach: Use an interface or abstract class DiscountStrategy. Each new discount type becomes a new class that implements this interface.

3. Liskov Substitution Principle (LSP)

"Subtypes must be substitutable for their base types."

Barbara Liskov is a pioneer who fundamentally changed how we write and organize code. Before her work in the 1970s, code was often a messy "spaghetti" of instructions. Liskov pioneered the concept of Data Abstraction. She led the team that created CLU, a programming language that introduced the idea of "abstract data types"—the direct ancestor of the "Classes" and "Objects" we use in almost every modern language like Java, Python, and C++. I hope you enjoyed that little history lesson. Let's proceed.

This principle states that if a program is using a base class, it should be able to use any of its subclasses without knowing it or causing errors. The subclass must honor the "contract" of the parent class.

  • Example: A classic violation is the "Square-Rectangle" problem. If a Square inherits from Rectangle but throws an error when the height and width are set to different values, it breaks the program's expectations.
  • Better Approach: If a subclass cannot perform the actions of the parent in the same way, they likely shouldn't share that specific inheritance hierarchy.

4. Interface Segregation Principle (ISP)

"Clients should not be forced to depend on methods they do not use."

I've seen this many times! You have to implement an interface in order to use a specific API call. You do this but realise you have to implement functions you are not interested in, leading to the dreaded "not implemented" comment. This can be partly remedied by using the Adapter Pattern by the way if you come across it.

It is better to have many small, specific interfaces than one large, "fat" interface. This prevents implementing classes from being burdened with "dummy" methods that do nothing.

  • Example: An IMachine interface with Print(), Scan(), and Fax(). A basic Printer class would be forced to implement Scan() and Fax() even if it can't perform those actions.
  • Better Approach: Break the interface into IPrinter, IScanner, and IFax machine.

5. Dependency Inversion Principle (DIP)

"Depend on abstractions, not concretions."

High-level modules (the logic) should not depend on low-level modules (the tools). Both should depend on abstractions (interfaces). This "decouples" the code, making it easy to swap out components.

This is great for writing tests, and you should be writing tests, many, many tests!! It allows you to easily mock the dependencies.

  • Example: A NotificationService that directly creates an instance of EmailSender. If you want to switch to SMSSender, you have to rewrite the NotificationService.
  • Better Approach: The NotificationService should depend on an IMessageSender interface. You can then "inject" whichever sender you need at runtime.

Conclusion

At the end of the day, SOLID is about managing change. Requirements shift, APIs evolve, and businesses pivot.

By following these five principles, you aren't just writing code for today; you’re leaving a map for the developer who has to touch this file six months from now. It turns software from a fragile house of cards into a robust, modular system.

Before I go, here is a test. Write some code. Store it away for a year. Look at your code. Is it still readable, understandable. Is is SOLID?

Comments and sharing

In our post, we mastered Mutations. We can now query, add, update, and delete films from our Hammer collection. However, every time we restart our Apollo server, our changes vanish into the ether. Our "Watched" list resets, and that film we deleted? It's back from the dead—and not in a cool, technicolor, cinematic way.

To fix this, we need Data Persistence. In this post, we’ll swap our humble, local JavaScript array for a MongoDB database.

If you haven't done so already, clone the lab Github repository using

bash
git clone https://github.com/jmwollny/lab.git

Install MongoDB

I'm installing on a Mac, if you what to install MongoDB on other systems go to the MongoDB download page here.

bash
brew tap mongodb/brew
brew install mongodb-community

Now start the MongoDB server. This command ensures that the MongoDB server will restart at logon.

bash
brew services start mongodb/brew/mongodb-community

Now check we have a running instance. Type mongosh. If the shell appears you are golden and are ready to proceed to the next section. Type exit to leave the shell.

Setting Up the MongoDB connection

First, we need to install the MongoDB driver. In your terminal, run:

bash
cd lab/graphql-tutorial-3
npm install mongoose

Mongoose is an Object Data Modeling (ODM) library that makes talking to MongoDB from Node.js much easier. If you open index.js you will see that the films array has been replaced with a MongoDB connection to a database called hammer_films.

javascript
const mongoose = require('mongoose');

// Connect to your local or Atlas MongoDB instance
mongoose.connect('mongodb://localhost:27017/hammer_films', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => console.log('Connected to MongoDB!'));

Defining the Data Model

In GraphQL, we have a Schema. In MongoDB (via Mongoose), we have a Model. These two need to mirror each other so our data flows correctly. A new file called Film.js contains the MongoDB model which has been exported so it can be shared by seed.js(more about this later!).

javascript
const mongoose = require('mongoose');

const filmSchema = new mongoose.Schema({
  title: { type: String, required: true },
  year: { type: Number, required: true },
  watched: { type: Boolean, default: false }
});

// Export the model so both index.js and seed.js can use it
module.exports = mongoose.model('Film', filmSchema);

Updating the Resolvers

This is where the magic happens. Instead of using .find() or .splice() on a local array, we will use Mongoose methods which return Promises. GraphQL handles these asynchronous calls automatically.

The New Queries and mutations

javascript
const resolvers = {
  Query: {
    films: async (parent, args) => {
      // 1. Build a dynamic query object
      let query = {};

      // Watch filter
      if (args.watched !== undefined) {
        query.watched = args.watched;
      }

      // Year filter (Exact match)
      if (args.year) {
        query.year = args.year;
      }

      // Date range filter (using MongoDB operators $gte and $lte)
      if (args.where) {
        query.year = query.year || {}; // Initialize year object if it doesn't exist
        if (args.where.year_gte) {
          query.year.$gte = args.where.year_gte;
        }
        if (args.where.year_lte) {
          query.year.$lte = args.where.year_lte;
        }
      }

      // Search filter (using Regex for case-insensitive partial match)
      if (args.searchTerm) {
        query.title = { $regex: args.searchTerm, $options: 'i' };
      }

      // Execute the query against the database
      return await FilmModel.find(query);
    },

    // Find by ID - Mongoose maps GraphQL 'id' to MongoDB '_id' automatically
    film: async (parent, args) => await FilmModel.findById(args.id),
  },

  Mutation: {
    addFilm: async (parent, { input }) => {
      // Create a new instance and save it
      const newFilm = new FilmModel(input);
      return await newFilm.save();
    },

    updateWatched: async (parent, { id, watched }) => {
      const updatedFilm = await FilmModel.findByIdAndUpdate(
        id,
        { watched },
        { new: true }, // This flag returns the record *after* it was updated
      );

      if (!updatedFilm) {
        throw new Error('Film not found');
      }

      return updatedFilm;
    },

    deleteFilm: async (parent, { id }) => {
      const deleted = await FilmModel.findByIdAndDelete(id);
      if (!deleted) {
        throw new Error('Film not found');
      }

      return await FilmModel.find();
    },
  },
};

Testing Persistence

Restart your server with node index.js. Now, head back to your GraphQL sandbox at http://localhost:4000/. We can test that after adding a film and restarting our Apollo server, the film still exists!

In the sandbox run a mutation to add a new film.

graphql
mutation CreateFilm($input: CreateFilmInput!) {
  addFilm(input: $input) {
    id
    title
    year
    watched
  }
}

Remember to add the variables JSON.

json
{
  "input": {
    "title": "The Brides of Dracula",
    "year": 1960,
    "watched": false
  }
}

Run the query then shut down your server (Ctrl + C in the terminal). Start the server again usig node index.js

Run a query to retrieve all films.

graphql
query GetAllFilms {
  films {
    id
    title
    watched
    year
  }
}

Query result

json
{
  "data": {
    "films": [
      {
        "id": "69dfb8e8067cfb4bcaadeb6d",
        "title": "The Brides of Dracula",
        "watched": false,
        "year": 1960
      }
    ]
  }
}

If all has gone well, your data is still there! Unlike our local array, MongoDB has written this data to the disk.

Why use Mongoose with GraphQL?

You might notice that our FilmModel and our GraphQL type Film look very similar. This redundancy is actually a strength. The GraphQL Schema acts as a contract for your frontend (telling it what data it can ask for), while the Mongoose Model acts as a gatekeeper for your database (telling it how the data must be stored).

The "ID" Gotcha

MongoDB uses a field called _id by default. GraphQL usually expects id. Mongoose is smart enough to provide a virtual id field that maps to _id, so the existing queries like film(id: "...") continue to work without a hitch.

Importing the full list of films

Let's finish by importing our film list into MongoDB, then we can get down to the fun job of watching every one and marking them as watched as we go.

To do this I have provided a handy script. Running the script will clear the database and import all films. All you need to do is open a terminal and run node seed.js.

bash
node seed.js
Connected to MongoDB for seeding...
Old records removed.
157 Hammer films successfully added to the database!

Let's have a look at the script.

javascript
const mongoose = require('mongoose');
const fs = require('fs');
// Import your Mongoose model
const Film = require('./models/Film'); 

const seedDatabase = async () => {
  try {
    // Connect to MongoDB
    await mongoose.connect('mongodb://127.0.0.1:27017/hammer_films');
    console.log("Connected to MongoDB for seeding...");

    // Read the JSON file
    const data = JSON.parse(fs.readFileSync('./films.json', 'utf-8'));

    // Clear existing films
    await Film.deleteMany({});
    console.log("Old records removed.");

    // Bulk insert the data
    await Film.insertMany(data);
    console.log(`${data.length} Hammer films successfully added to the database!`);

    // Close the connection
    process.exit();
  } catch (error) {
    console.error("Error seeding database:", error);
    process.exit(1);
  }
};

seedDatabase();

This script does the following:

  • Connects to MongoDB
  • Parses the list of films(note: we do not need the id anymore in the JSON)
  • Deletes all records in the database
  • Inserts all records defined in the JSON file

Conclusion

We’ve successfully moved our Hammer database from a "temporary" state to a "permanent" one. By integrating MongoDB, we've laid the groundwork for a real-world application. We are no longer just playing with variables in memory. we are managing a persistent data store. As an exercise try creating different queries or if you are feeling brave add more fields to the schema. Have fun coding and if you feel inclined watching one of the suggested films :-)

Comments and sharing

In our last post, we built a robust way to search through 157 Hammer classics. But what happens when you finally sit down to watch The Brides of Dracula? You need a way to update that record.

In GraphQL, any operation that changes data is called a Mutation.

If you have not followed part 1 of this tutorial go there now to pull the code from my Github repository.

1. Updating the Schema

First, we need to tell our server what these changes look like. We’ll add a Mutation type to our typeDefs. We have one to update a film entry(updateWatched) and one to delete a film(deleteFilm).

graphql
type Mutation {
  # Toggle the watched status of a film
  updateWatched(id: ID!, watched: Boolean!): Film
  
  # Delete a film from our collection
  deleteFilm(id: ID!): [Film]
}

2. Writing the Resolvers

Now, we implement the logic to update and delete a film record. Since we’re working with a local array of films data we’ll use standard JavaScript array methods to find and modify our data. Here we are using splice and find.

javascript
const resolvers = {
  // ... query resolvers
  
  Mutation: {
    updateWatched: (parent, { id, watched }) => {
      const film = films.find(f => f.id == id);
      if (!film) {
        throw new Error("Film not found");
      }
      
      film.watched = watched;
      return film;
    },
    
    deleteFilm: (parent, { id }) => {
      const index = films.findIndex(f => f.id == id);
      if (index == -1) {
        throw new Error("Film not found");
      }
      
      // Remove the film and return the updated list
      films.splice(index, 1);
      return films;
    }
  }
};

3. Testing in the Playground

Once you restart your server, you can test these live.

bash
node index.js
🚀 Server ready at http://localhost:4000/

Navigating to http://localhost:4000/ will redirect to the GraphQL sandbox. Click the 'Query your server' button and you will be presented with something like this.

First of all we need to find all unwatched Dracula films returning the id. Quick quiz! Do you remember how to craft the query? Here it is:

graphql
query GetNotWatched {
  films(watched: false, searchTerm: "dracula") {
    id
    title
  }
}

This will return the following.

json
{
  "data": {
    "films": [
      {
        "id": "70",
        "title": "The Brides of Dracula"
      },
      {
        "id": "102",
        "title": "Dracula: Prince of Darkness"
      },
      {
        "id": "115",
        "title": "Dracula Has Risen from the Grave"
      },
      {
        "id": "122",
        "title": "Scars of Dracula"
      },
      {
        "id": "125",
        "title": "Countess Dracula"
      }
    ]
  }
}

Pick a film and remember the ID. This will be used in the next step. In my case I will pick the first film which has an id of 70.

Mark "Brides of Dracula" (ID: 70) as watched:

Paste this query into the sandbox(remember to substitute your own id if it is different).

graphql
mutation {
  updateWatched(id: "70", watched: true) {
    title
    watched
  }
}

After running the update query run the GetNotWatched query again to check that the film is not in the list.

Removing a film

Let's remove "Brides of Dracula".

graphql
mutation {
  deleteFilm(id: "70") {
    title
  }
}

If we run a query to return the film with id 70 GraphQL will now return null.

graphql
query GetFilm {
  film(id: 70) {
    id
    watched
    year
  }
}

Results from the query

graphql
{
  "data": {
    "film": null
  }
}

Adding a film

Let's add the film back!

When adding a record, passing four separate arguments (ID, Title, Year, Watched) can get messy. Instead, we define an input type in our schema to group them together.

Update the Schema

We create a new input which specifies which fields are mandatory when creating a new Film. In our case all fields must be specified(indicated by the "!"). This input spec is then specified in our addFilm mutation.

graphql
input CreateFilmInput {
  id: ID!
  title: String!
  year: Int!
  watched: Boolean!
}

type Mutation {
  # ... previous mutations
  addFilm(input: CreateFilmInput!): Film
}

Update the Resolver

javascript
const resolvers = {
  Mutation: {
    // ... updateWatched and deleteFilm
    
    addFilm: (parent, { input }) => {
      // Check if ID already exists to prevent duplicates
      const exists = films.find(f => f.id === input.id);
      if (exists) {
        throw new Error("A film with this ID already exists.");
      }

      const newFilm = { ...input };
      films.push(newFilm);
      return newFilm;
    }
  }
};

Testing the "Add" Mutation

Enter the query into the sandbox

graphql
mutation CreateNewHammerFilm($input: CreateFilmInput!) {
  addFilm(input: $input) {
    id
    title
    year
  }
}

Under the query box, enter the variables JSON.

json
{
  "input": {
    "id": "70",
    "title": "The Brides of Dracula",
    "year": 1960,
    "watched": false
  }
}

After running the mutation you can run the GetFilm query, which will show the resurrected film in all its glory!

graphql
query GetFilm {
  film(id: 70) {
    id
    watched
    year
  }
}

Why use input types?

Using an input object instead of flat arguments makes your API much more maintainable. If you decide to add a director or studio field later, you only have to update the input type, rather than changing the signature of the mutation across your entire codebase.

Why "Mutation" instead of "Query"?

While you could technically change data inside a Query resolver, it’s a major "no-go" in the GraphQL world. Using the Mutation keyword tells the server (and other developers) that this operation has side effects. It also ensures that if you send multiple mutations in one request, they run serially (one after another) to prevent data race conditions.

Conclusion

We’ve come a long way from a simple JavaScript array of my favourite films. By implementing Mutations, we’ve transformed our Hammer dataset into a functional API. We can now:

  • Create new entries to keep our database growing.
  • Update existing records to track our viewing progress.
  • Delete entries to keep our data clean and accurate.

This "CRUD" (Create, Read, Update, Delete) cycle is the backbone of almost every application you use daily. While we are currently managing this data in local memory via a simple array, the patterns we’ve used here—Input Types, Non-Nullable arguments, and Serial Mutation execution—are the exact same patterns you would use when connecting to a production-grade database like MongoDB or PostgreSQL.

What's Next?

Now that the backend logic is solid, the next logical step is to explore Data Persistence. In the next post, we'll look at how to hook this GraphQL server up to a database so that our "Watched" status doesn't disappear every time we restart the server!

Until then, happy coding!

Comments and sharing