GraphQL Basics with Express and MongoDB

Ahmet Biçer
HardwareAndro
Published in
6 min readSep 7, 2020

Software developers are familiar with REST and RESTful API systems. It is a go to for API services but it has some shortcomings when the application starts to scale and the number of endpoints start to raise. This is causing inefficiency and maintaining issues for developers. This is why Facebook introduced GraphQL in 2015.

GraphQL “A query language for your API”.

When we think about general API systems, we are trying to reach our data source and get the data we want. In order to do that in REST we need to create endpoints and send a request to get the data that endpoint provides. I write that in bold because it is what the problem with REST API’s. They are not dynamic. You can’t get more data from that endpoint. If you want more data you need to write more endpoints.

Photo Credit: https://davidwalsh.name/getting-started-with-graphql

This is what GraphQL solves. We are only creating one endpoint. In order to get all the data we need from that endpoint GraphQL has to know how we are storing our data in our database and what are the relationships between different objects.

Creating a MongoDB Model

At first we are going to create two models in our MongoDB database.

The first one is a User Model.

This is a very simple user model, it only has a name field with type string. We are using Mongoose to connect and use our database. We don’t need to give a id field because mongoose automatically creates id when we create a new User.

The other one is Product Model.

Product model has 4 different fields which are name, stock, cost of the product and a sellerId field to create relationship between user and product models. So every user can have many products.

After creating our models. We need to create our GraphQL types. They are going to describe how we are storing our data in our MongoDB database.

Describing our data with GraphQL Types

In line 14 we created a GraphQLObjectType with name UserType, and in line 28 we do the same thing but for ProductType. These are going to describe our MongoDB models to GraphQL. Fields are pretty self explanatory but we need to pay attention to relationships between this two types. In line 19, the products field has a type of GraphQLList(ProductType). So every user can have a list of products. In the resolve function we are connecting to our db and returning the products with sellerId of parent.id . The parent object has the id of that user. We do the similar thing to ProductType to get the seller of that product.

We finished the describing part, now we need to create some Root Queries to start getting our data.

Root Queries

In order to get the data we just described, we need to create some Root Queries. If we think GraphQL as a graph data structure, the types we defined earlier will be the nodes. Root Queries defines how we are jumping between different nodes in the graph.

In this code snippet we created 4 different root queries. Which are user, product, users and products. We are using user and product root queries to get user or product by their id. We can see in the args object we need to pass an id to use this query. “Users” and “products” root queries returns all the users and products in our db. We will see how we can use this queries in the end of the article.

We defined our types and root queries but if we don’t have any data in the db we can’t use either of them. So we need a way to create this types. These are called mutations in GraphQL world.

Mutations

In order to do CRUD operations in GraphQL we need to create mutations.

In this code snippet we created two mutations. The first one adds a user and the other one adds a product to our MongoDB. In the args object, we defined what we need to create this object (e.g name for user type) and in the resolve function, we created an entry in our MongoDB using the arguments provided by user. Lastly we need to export our root queries and mutations into a GraphQLSchema object like below.

We created our MongoDB models, GraphQL types, root queries and mutations. Hang tight we just need to combine all of them to start a express server and start playing with queries.

Express Server

This is a basic setup to create a express server in port 3000. Do you remember that i said we just need one endpoint. In line 15 we created that endpoint in /graphql. Line 17 is important we need to set the graphiql parameter to true to get a user interface for testing our GraphQL server.

We are all set! Start the server and go to localhost:3000/graphql. You will see a user interface like this.

Left side where we are writing our queries. Right side will show the results. In the far right side we have the documentation explorer

Documentation Explorer

Documentation explorer is a super helpful tool that shows our root queries and mutations and how we can use them. (it is similar to swagger)

Left: Shows our root queries and mutations. Middle: Shows our root queries and how we can use them. Right: Shows our mutations and how we can use them.

Lets Write Some Queries

Use users root query and get id and name of that users
Left: Use users root query and get name and products of that users. Right: Same query with stock information

Did you see how easy to get different data for our needs? If we try to do this in a REST API we need to write two endpoints.

Left: Use products root query and get name of that products. Right: Same query with seller information.

Because we defined the relationship between user and product we can access the seller data in the same query!

Get product or user by id root queries

Lets add some data with mutations

Left: Use addUser mutation and if the mutation successful return the name. Right: Use addProduct mutation and if the mutation successful return the name.

That’s All! We are describing our data and the relationships. After that GraphQL handles all of the queries!

Thanks for reading. You can find the full code in my github.

--

--