In this guide, I am going to show how you can easily set up a GraphQL API layer for your MongoDB using Space Cloud in a couple of minutes.

The keyword to note here is instant. Which means you won’t have to write a GraphQL backend yourself. Sounds like a magic right? Let me explain it to you in a minute.

Table of contents

MongoDB and GraphQL Intro

MongoDB is one of the most popular NoSQL databases out there. The developer agility provided by the schemaless nature of MongoDB is one of the biggest reason for its widespread adoption. Not to forget that MongoDB is also highly scalable as compared to a traditional relational database. If you have a heavy write workload with an evolving schema, then MongoDB might be ideal for you.

GraphQL, on the other hand, is a query language for your APIs, gradually replacing REST. It allows you to describe your data needs precisely and provides you with the exact data you had asked for, solving age-old under fetching and over fetching problems. If you are new to GraphQL and want to learn more about it, check out its official site.

However, to avail these excellent benefits, you need to set up a GraphQL API on the backend by writing resolvers. Having to write a GraphQL server adds friction to its adoption. While there are many GraphQL implementations for SQL databases, most of them require you to have a schema and don’t work out of the box with MongoDB because of its schemaless nature. That’s where Space Cloud comes into the picture by providing schemaless GraphQL APIs for your MongoDB without writing a backend. So, let’s see what Space Cloud is all about.

What is Space Cloud?

To keep things simple,

Space Cloud is an open-source web server which provides instant GraphQL and REST APIs on the database of your choice.

The coolest part about Space Cloud is that all the APIs are realtime. You can optionally subscribe to changes in the database. This functionality comes in handy while making real-time apps.

Since Space Cloud also has a robust security module built into it, you can consume these APIs directly from the frontend. So in most use cases, just making an Angular or React app using the Space Cloud APIs should be the only code you write!

To show your support❤️, ️️ you can give it a star on Github.

What if I don’t use MongoDB?

Space Cloud provides GraphQL APIs for MongoDB, Postgres and MySQL (and their compatible databases) out of the box. If you use any other database apart from MongoDB, then these guides can help you get started:

Cool, that’s enough of history and features. Let’s dive straight into it!

Getting started with GraphQL and MongoDB

In this guide, we are going to building a simple blogging application on top of MongoDB, which has authors and posts.

Each author can have multiple posts, whereas a post can only belong to a single author. Note that this is a one-to-many relation.

Note: Don’t worry if you get stuck somewhere. You can always ping me on our Discord channel.

Setup

We are using Docker Compose to run both Space Cloud and MongoDB for us.

Step 1: Get the docker-compose file

The spaceuptech/space-cloud/install-manifests repo contains all installation manifests required to deploy Space Cloud anywhere. Get the docker-compose file from there:

wget https://raw.githubusercontent.com/spaceuptech/space-cloud/master/install-manifests/quick-start/docker-compose/mongo/docker-compose.yaml

You should be able to see a docker-compose.yaml file with the following contents:

version: '3.6'
services:
  mongo:
    image: mongo
    restart: always
  space-cloud:
    image: spaceuptech/space-cloud
    ports:
    - "4122:4122"
    - "4126:4126"
    depends_on:
    - "mongo"
    restart: always
    environment:
      ## The DEV environment lets you use Mission Control (Admin UI) without login
      ## Change the dev mode to false if you want a login to your Mission Control UI
      DEV: "true"
      ## Uncomment next lines to change the login credentials of Mission Control UI
      # ADMIN_USER: "admin"
      # ADMIN_PASS: "123"
      # ADMIN_SECRET: "some-secret" # This is the JWT secret used for login authentication in Mission Control

Step 2: Run Space Cloud & MongoDB

docker-compose up -d

Check if the containers are running:

docker ps

Step 3: Configure Space Cloud

If you exec into docker container of Space Cloud, you can see a config.yaml file generated by Space Cloud in the home directory.

Space Cloud needs this config file to function. The config file is used to load various information like which databases to use, their connection strings and security rules.

Space Cloud has it’s own Mission Control (admin UI) to configure all of this quickly.

Open Mission Control:

Head over to http://localhost:4122/mission-control to open Mission Control.

Note: Replace localhost with the address of your Space Cloud if you are not running it locally.

Create a project:

Click on Create a Project button to open the following screen:

Give a name to your project.

MongoDB is selected as your database by default. Keep it as it is and hit Next to create the project.

Configure database module:

Head over to the Database section:

Click Edit Connection button to open the following form:

Copy-paste the following connection string in it:

mongodb://mongo:27017

If the connection was successful, you should be able to see something like these:

Great! That’s all that is required to configure Space Cloud. It’s time to play around with MongoDB using the auto-generated GraphQL APIs.

Running GraphQL queries on Space Cloud

Mission Control has an embedded GraphiQL IDE which lets us fire queries without having to build a frontend.

Head over to the Explorer section.

Let’s start by creating some authors and posts, which translates to inserting a few documents in your MongoDB.

Inserting data

Inserting data into our MongoDB is as simple as firing a GraphQL query for us. Try running the following GraphQL query to create few authors:

mutation {
 insert_author(
   docs: [
    { _id: "1", name: "Dan"},
    { _id: "2", name: "Ryan"}
  ]
 ) @mongo {
   status
 }
}

On successful insert, you should be able to see the status as 200 which means you have successfully inserted the documents in your MongoDB.

The docs argument is nothing but the array of documents that you want to insert in your collection.

If you have noticed, we have used a @mongo directive in the above query. For Postgres or MySQL, change it to @postgres or @mysql respectively. And that’s it!

Inserting posts should be a no brainer now. Just run the following GraphQL query to insert some posts:

mutation {
 insert_post(
    docs: [
      { _id: "1", author_id: "1", title: "Introducing Hooks" },
      { _id: "2", author_id: "1", title: "React vs Vue" },
      { _id: "3", author_id: "2", title: "Context API" },
      { _id: "4", author_id: "2", title: "React + Redux" }
    ]
 ) @mongo {
   status
 }
}

Querying data with filters

Having inserted authors and their posts, let’s try to query posts of a particular author. It’s nothing but a filtering operation.

Try running the following query in the GraphiQL editor:

query {
 post (
   where: {author_id: "1"}
 ) @mongo {
   _id
   title
 }
}

As you can see, we only got the posts that belonged to author_id 1. Check out this guide for a complete list of filtering options.

Updating data

Updates require two information - a where clause to filter the documents to be updated and at least one update operator.

Let’s say you want to update the name of a particular author in your MongoDB. Here’s a GraphQL query to do it:

mutation {
 update_author (
   where: { _id: "2"},
   set: {name: "Ryan Florence"}
 ) @mongo {
   status
 }
}

You can also perform various operations like incrementing, decrementing, multiplying. Check out this guide for a complete list of update operations.

Performing joins

Now comes the fun part, i.e. Performing join operations on your MongoDB directly from the frontend. Joins are used to fetch data for a type along with data for a related type.

Note: MongoDB does not provide joins out of the box. However, Space Cloud makes it possible to perform joins via its GraphQL API.

Let’s say we want to show a list of authors along with the title of their posts. In essence, it’s a database join operation. Here’s how you would do it using Space Cloud:

query {
 author @mongo {
   _id
   name
   post(
     where: {author_id: "author._id"}
   ) @mongo {
     title
   }
 }
}

The response should look something like this:

{
  "authors": [
    {
      "_id": "1",
      "name": "Dan",
      "post": [
        {
          "title": "Introducing Hooks"
        },
        {
          "title": "React vs Vue"
        }
      ]
    },
    {
      "_id": "2",
      "name": "Ryan Florence",
      "post": [
        {
          "title": "Context API"
        },
        {
          "title": "React + Redux"
        }
      ]
    }
  ]
}

Notice how we are matching the parent query’s result authors._id with the nested query’s field author_id to perform a join operation. Read more about joins.

Note: Space Cloud optimizes the number of queries made to the database for fetching such kind of relational data using a pattern called dataloader.

Conclusion

Setting up an GraphQL layer on top of MongoDB is not that difficult. Just point Space Cloud to a MongoDB instance are you are good to consume GraphQL in your applications.

As an advantage, GraphQL opens up tons of new possibilities like performing joins on MongoDB which doesn’t provide joins out of the box. We are very excited about it and are going to double down on making our GraphQL support more robust.

The future, however, seems to be amazing. With the ability to do cross-database joins with MongoDB and other SQL databases mean we can build enterprise-grade apps that leverage the best of both worlds.

Show your support❤️ by giving it a star on Github.