Building a GraphQL API for User CRUD with Node.js and MongoDB
Tags: node, graphql, mongodb, beginners
Published: 2023-06-04 09:40:40

In today's digital age, efficient data management is crucial for any application. GraphQL has emerged as a powerful tool for building flexible and performant APIs, while Node.js provides a scalable runtime environment. Combined with MongoDB, a popular NoSQL database, we have the perfect stack for creating a robust user CRUD (Create, Read, Update, Delete) API. In this post, we will explore how to build a GraphQL API using Node.js and MongoDB.

### Prerequisites:
Before diving into the implementation, make sure you have the following prerequisites installed on your machine:

1. Node.js: Download and install the latest version of Node.js from the official website.
2. MongoDB: [Install MongoDB Community Edition](https://www.mongodb.com/docs/manual/installation/) and start the MongoDB service.

Step 1: Setting up the Project

To begin, create a new directory for your project and initialize it as a Node.js project by running the following command:

```bash
mkdir graphql-api && cd graphql-api
npm init -y
```

Next, install the necessary dependencies: Express, Express-GraphQL, Mongoose, and GraphQL.

```bash
npm install express express-graphql mongoose graphql
```

Step 2: Creating the MongoDB Schema

In this step, we will define the structure of our user data by creating a schema. Create a new file called `models/User.js` and add the following code:

```javascript
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  }
});

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

```

Step 3: Setting up the GraphQL Schema

The GraphQL schema defines the operations and data types available in our API. Create a new file called `graphql/Schema.js` and add the following code:

```javascript
const { buildSchema } = require("graphql");

const schema = buildSchema(`
  type User {
    id: ID!
    name: String!
    email: String!
    password: String!
  }

  type Query {
    getUser(id: ID!): User
    getUsers: [User]
  }

  type Mutation {
    createUser(name: String!, email: String!, password: String!): User
    updateUser(id: ID!, name: String, email: String, password: String): User
    deleteUser(id: ID!): User
  }
`);

module.exports = schema;
```

Step 4: Implementing the GraphQL Resolvers

Resolvers are functions that handle the GraphQL operations defined in the schema. Create a new file called `graphql /Resolvers.js` and add the following code:

```javascript
const User = require("../models/User");

const resolvers = {
  getUser: async ({ id }) => {
    try {
      const user = await User.findById(id);
      return user;
    } catch (err) {
      throw new Error("Error retrieving user");
    }
  },
  getUsers: async () => {
    try {
      const users = await User.find();
      return users;
    } catch (err) {
      throw new Error("Error retrieving users");
    }
  },
  createUser: async ({ name, email, password }) => {
    try {
      const user = new User({ name, email, password });
      await user.save();
      return user;
    } catch (err) {
      throw new Error("Error creating user");
    }
  },
  updateUser: async ({ id, name, email, password }) => {
    try {
      const user = await User.findByIdAndUpdate(
        id,
        { name, email, password },
        { new: true }
      );
      return user;
    } catch (err) {
      throw new Error("Error updating user");
    }
  },
  deleteUser: async ({ id }) => {
    try {
      const user = await User.findByIdAndRemove(id);
      return user;
    } catch (err) {
      throw new Error("Error deleting user");
    }
  },
};

module.exports = resolvers;
```

Step 5: Creating the Server

Now, let's create the server that will handle the GraphQL requests. In a new file called `index.js`, add the following code:

```javascript
const express = require("express");
const { graphqlHTTP } = require("express-graphql");
const mongoose = require("mongoose");
const schema = require("./graphql/Schema");
const resolvers = require("./graphql/Resolvers");

const app = express();

// Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/graphql-demo", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
mongoose.connection.once("open", () => {
  console.log("Connected to MongoDB");
});

app.use(
  "/",
  graphqlHTTP({
    schema,
    rootValue: resolvers,
    graphiql: true,
  })
);

app.listen(3000, () => {
  console.log("Server running on http://localhost:3000/");
});
```

Step 6: Starting the Server

To start the server, run the following command in your project directory:
```
node index.js
```

Congratulations! You have successfully built a GraphQL API for user CRUD operations using Node.js and MongoDB. With this setup, you have a flexible and efficient API that allows you to create, retrieve, update, and delete user data with ease. Remember to handle errors gracefully and enhance the API based on your specific requirements. Feel free to extend this example to include additional functionality or integrate it into your own projects. Happy coding!