The Beginner’s Guide to using GraphQL with Node and Mongo — Part I
Today, let’s learn how to hook up MongoDB with GraphQL using Apollo Server and Mongoose.
Before starting, you will need the following already set up on your machine:
Please have these set up before continuing with this tutorial.
Create Directory and Install Packages
In your coding directory, create a new folder you will be working in. Change your current directory to that new folder and create a new folder to hold your server code in and run npm init -y
.
mkdir server
cd server
npm init -y
This will create the package.json
file for us.
Next, we will install a few libraries:
npm install apollo-server-express express graphql mongoose nodemon
After running npm install
, create index.js
file in the root of server
.
Connecting Apollo Server
In index.js
, we will first connect Apollo-server
.
In Lines 1–2, we first import express
, ApolloServer
, and gql
so we can use it in our code.
In Lines 4–8, we define the types by implementing the typeDefs
object needed for ApolloServer
in Line 16. gql
lets us write GraphQL syntax in JavaScript. In Lines 5–6, we create a GraphQL Query
type. Line 6 is the name of one of the Querys we are making. A Query
is similar to doing a GET
, where you are just retrieving data.
In Lines 10–14, we implement the resolvers
object needed for ApolloServer
in Line 16. This is where we implement what the Query
actually does. In Line 12, we implement the hello
query to just give back 'Hello World'
.
In Line 16, we create our ApolloServer
and pass in an object with typeDef
and resolver
as a parameter.
In Line 17–18, we apply Express
as our server middleware, but we aren’t doing anything with Express
in this part.
In Line 20, we have our ApolloServer
listen on port 4000
, and when it’s ready, it will print in the console that it is ready to run.
Testing the GraphQL Query
If we open a terminal to the directory that has index.js
in it and run npm start
, we should have the GraphQL Playground open.
For those unfamiliar with the Playground, you’re able to make GraphQL queries on the left side, and see the data that is queried back on the right side.
We can test our new query on the left side like this:
query hello {
hello
}
query
lets GraphQL know that we are trying to do a query
type. The hello
after the query is giving our query a name (similar to how you name a function). Inside the curly braces, we then use hello
, which is the Query we made in Line 6 of our index.js
.
Pressing the Play button will return the data for hello
— which was 'Hello World'
.
Connecting MongoDB
Let’s get MongoDB connected with our Apollo Server now.
First create a file called config.js
. We will make the MongoDB connection with config.js
. In my MongoDB, I created a database called graphqldb
. I also use the default MongoDB port 27017
.
To connect it, add this line to your index.js
after the require statements at the top.
require('./config');
Create MongoDB User Schema
Now we need to create a schema for our MongoDB. I’m going to create a simple User
schema.
First create a models.js
in the root of your project.
Here we create a userSchema
and give it just a userName
and an email
.
We can now add it to our index.js
file. Place this line after your config
require:
const { User } = require('./models');
Updating GraphQL Queries and Adding Mutations
Now that we have MongoDB to work with, we’re going to update GraphQL queries and add mutation types.
In Lines 8–12, we create a new GraphQL type: User
. We are saying that anything that is a User
type will require an ID
that is type ID
(unique identifier), and can have a userName
that is typeString
, and an email
that is also typeString
. The !
operator means it cannot be null.
In Lines 14–16, we replace our hello
query with a getUsers
query that returns an array of type User
. This means getUsers
MUST an object that has an id
, userName
, andemail
to satisfy a User
type, otherwise it will return nothing.
In Lines 18–20, we add a Mutation
type to our typeDefs
. Mutations
change the data, similar to a POST
, PUT
, or DELETE
. On Line 19, we declare a addUser
function that requires a userName
, and email
, and that it will return a User
type.
In lines 23–37, we update our Resolvers
with the new Query
and Mutation
.
Lines 24–26, we make a call to MongoDB using Mongoose and retrieve all Users
from the Users
collection. This will return Users
based on the MongoDB schema — which has an id
, userName
, and email
— which matches the GraphQL User
type.
Lines 27–36, we also make a call to MongoDB using Mongoose to create a new User
. We pass in two parameters — the first one is _
because we aren’t using the parent parameter, and the second one are the args
that we pass in the mutation function ( userName
and email
). We then return the response
we get from MongoDB, and that also has the id
, userName
, and email
needed to complete a User
type.
Playing with the new query and mutation
Now that we have the new queries and mutations, we can go to the Playground and make a new query
and new mutation
.
Since we don’t have anything in our database, let’s do a mutation
first.
mutation addUser {
addUser(userName: "wyang", email: "wyang@gmail.com") {
userName
email
}
}
Here we are declaring that we are going to use a mutation
. We give it the name addUser
(this is not the same as the addUser
function we made in the typeDefs
, but rather just to give the mutation a name for the Playground). Inside of the mutation
, we use the addUser
function and we pass in our two parameters. We first declare the userName
parameter and give it the a string, and we do the same for email
. When we open up the curly braces, we ask it to return the userName
and the email
.
Now that we have something added to our database, we can now use our new getUsers.
To use it, let’s use this new query:
query getUsers {
getUsers{
id
userName
email
}
}
Once again, we declare we are making a query
and we are giving it the name getUsers
. Once again, the getUsers
that is declared after query
is the name of the query in the Playground, and not the actual query we made. Inside of this query
, we use the getUsers
function, and ask to return the id
, userName
, and email
.
Conclusion
We have done quite a few things in this part:
- Set up Apollo Server
- Created MongoDB Schema
- Implemented Queries and Mutations with Mongoose
In Part II, I will connect the front end with Apollo Client! Let me know what you liked, or what needs improving in the comments below.
I hope this tutorial was helpful!