CRUD Operation using GraphQL Apollo server with Nodejs and MongoDB

Creating a simple CRUD API app using GraphQL with NodeJs and MongoDB.

Rahil Shaikh
8 min readSep 14, 2022

GraphQL is a new API standard invented and developed by Facebook. It is an open-source server-side technology, now maintained by a large community of companies and individuals from all over the world. It is also an execution engine that works as a data query language and used to fetch declarative data.

The objective of developing GraphQL was to optimise the RESTful API calls and provide a flexible, robust, and more efficient alternative to REST. GraphQL is data query and manipulation language for your API

GraphQL serves many advantages when compared to REST calls, like Fetch only what you want, single api endpoint can be used to fetch different data as per need, GraphQL api are also lightweight as it only fetches data that is required rather than fetching all the data and then filtering the data to show the subset of data at frontend.

Our Objective

Our Learning Objective in this blog is to create an API app in Nodejs that will use GraphQL API endpoints to fetch, update, delete, insert the data in MongoDB.

We will learn this in 3 Simple Steps:

Step 1: Create a MongoDB DB and collection

Step 2: Create GraphQL queries in NodeJs to interact with MongoDB

Step 3: Creating a NodeJs Apollo Server to execute CRUD with GraphQL

We will focus more on Step 2 and Step 3.

Note that we are creating graphQL queries first and then the NodeJs Server, we are doing this on purpose so that we understand how to link our graphQL queries with MongoDB and NodeJs Apollo server.

Also find the git repository here for your reference: https://github.com/RaheelShaikh/graphql-nodejs-project

Let us get started with one step at a time

Step 1: Create a MongoDB Database and Collection

We will create a DB named products and a collection named productlists in mongo DB, you can give any name of your choice but if this is your first time I highly recommend you to follow exactly the same.

Add the following data fields in your collection:

productlists collection inside products DB in MongoDB

We will perform CRUD operation on this collection itself, i.e we will add, update, delete and fetch operations on productlists collection

Step 2: Create GraphQL queries in NodeJs to interact with MongoDB

So here’s where the actual coding starts.

We start with creating a new project by creating a new folder and naming it GraphQLNodeJS, now open this folder is your VS Code and in your VS terminal execute the below command

npm init command to initialise nodejs app

Now we will install the dependencies that we need for our Node App

execute the below command in your VS Code terminal

commands to install dependencies

apollo-server is used to create a graphQL server

apollo-server-express is used to integrate graphQL with express app

mongoose is MongoDB object modelling tool to interact with MongoDB

Once we are done with installing dependencies we will now create mongoose schema model for our collection that we created in Step 1

Create a new folder models in root of your project and add a file productSchema.js inside the models folder and add the below code

We will export this models as we will require this to perform CRUD operations on our collection.

Next we will add another file named graphQLSchema.js in root of our project, now this file contains the code for GraphQL queries and connect GraphQL to our mongoDB collection.

Before we start with the Code it is important to understand certain terms and syntax associated with GraphQL. Now GraphQL has two types of queries that are widely used

  1. Query: Used to fetch record, either all records or specific record by Id or any other condition, basically it is used for fetch/read operation
  2. Mutation: Used to perform Add, Update, Delete operations.

Defining a GraphQL Schema:

GraphQL queries requires a GraphQL Schema which is nothing but Schema of the collection that you need to query or in other words schema of the collection that you need to perform CRUD operation on, the Schema will have the name and type of the fields in the collection and ! will denote that the field is required. To denote whether a field is an unique identifier we use type as ID. Refere below syntax

type <your_schema_name> {<fieldName1>: <fieldType><fieldName2>: <fieldType>}

So for our productlists collection the schema will be

type Product {id: IDcategory: String!productName: String!price: Int!colors: [String!]}

We will use apollo-server-express to create Query, notice how we imported apollo-express-server below, also we will need to import mongoose and our mongoose model.

graphQLSchema.js

Once we have defined our schema we are now good to write queries, consider these queries as endpoints that we want so as to perform CRUD operations, we will add our queries inside graphQLSchema.js file

Under the type Query we will add two queries getProductList that will be used to fetch all the products in productlists collection and getProduct that will be used to fetch a specific product by its ID

Under type mutation we will add three queries updateProduct to update the product, addProduct to add a new record in productlists collection and deleteProduct to delete a product based on ID

Also create a function to connect to MongoDB

refer the code below, so the graphQLSchema.js file will now be

graphQLSchema.js

Now the final phase of Step 2 is to create a resolver. Consider resolvers as a link that connect queries to mongoDB so that we can perform operations in mongoDB collections based on queries. We will implement the queries here i.e write the code to perform CRUD in MongoDB using the model we created for productlists collection. In simple terms if queries are endpoints then resolvers are implementation of the endpoint.

We will group Query type queries and Mutation type Query together in resolver implementation. Implementation is nothing but to use mongoose MongoDB functions to perform find, update, delete, save operations in collection

here is the complete code for graphQLSchema.js file

graphQLSchema.js

Notice how we have exported typeDefs and resolvers so that we can use them in our app.js file which will be our server’s startup file. We are 90% done with the coding part.

Step 3: Creating a NodeJs Apollo server to execute CRUD with GraphQL

This is the final piece of our app, We will create a simple server which will accept the typeDefs and resolver (from Step 2 )and run the server on a specified port.

We will use apollo-sever for this which is used to create a NodeJS server for GraphQL.

There is not much code in this file, just a simple basic NodeJs server, refer code below

app.js

Notice how we have imported graphQLSchema,js file to pass parameters to ApolloServer instance.

We are done and ready Run our App

Run our app using node app.js command and open the app in browser in url http://localhost:9000/

command to run the app

You can query your endpoints in two ways, first by using Apollo Server GraphQL GUI and second by Postman, we will see both starting with Apollo Server GraphQL GUI

When you run your app you will see an interface as below, click on Query your Server button

node app running on http://localhost:9000/

Now let us first get all the products in collection using getProductsList Query, you will see two query types on the left panel click on query: Query type

on clicking query:Query type, all the calls inside query type i.e. getProductsList and getProduct will be populated on the left panel

Click the + icon beside getProductsList option, select the fields you want to fetch and execute the query by clicking GetProductsList Button at the top right corner and you should get the output as list of all the products

Now you can also unselect some fields, let’s say that we need only productName and price then we can simply unselect other fields from left panel and run the query again to get just the list of productName and price as below

getProductsList now only fetches productName and price

Let us now fetch products by an ID using getProduct query which accepts and ID of product to fetch

getProduct by id

Notice how we have passed id of product to fetch to the variables section at the below.

Let us now Query Mutations:

We will start with adding a new product using addProduct query as below

addProduct query to add a new Product

Notice here that we have selected the arguments that we want to pass and fields we need in response on the left panel also we have provided the values against each argument on the variables panel below, click the Mutation button and you will get the added product as output, now you can hit the getProductsList query and you should get the newly added Product in the list of products as output.

For updateProduct you can pass the updateProductId as parameter to the query and values that you need to update as below

for deleteProduct you have to pass the ID of the product as deleteProductID you want to delete as parameter, you should get output as true which means your product is deleted, go ahead and hit the getProductsList query again and see your product is now not fetched in the output list as it has been delete from DB.

Execute graphQL endpoint from Postman:

To achieve this you just click on the three dots below the UpdateProduct button and click on Copy Operation to CURL

Copy operation to CURL

Open postman, click on import button and paste the curl as raw text, click continue and then click on import, your request will be generated in postman.

request generated in postman
generated postman request

Now hit send and you should get output of updateProduct api

updateProduct api output

Similarly you cab generate CURL for all other requests and hit the same using postman.

End Notes:

We have seen how we can implement graphQL api using NodeJs and mongoDb and consume the api using postman, you can now dig in further in detail about graphQL as now you must have gained basic concepts of graphQL integration with NodeJs and MongoDB

If you like the blog then give some claps👏 and share with your friends !!

--

--

Rahil Shaikh

Senior Software Engineer | Machine Learning, Node.js, Angular, C#. Loves Travelling, Photography.| Learn something new every day.