GraphQL is a query language for APIs as is a server-side runtime for executing queries by using a type system that you have defined for your data. Express JS is a free open-sourced framework for NodeJS used to build web applications. Express is a lightweight framework that runs on top of Node.js’ web server facilities to make APIs easier to use and add useful new features. MongoDB is a document database to store and query data. Working with massive sets of distributed data is a breeze with NoSQL databases. MongoDB is a database management system that can store, retrieve, and manage document-oriented data.

This article dives into what GraphQL NodeJS MongoDB are and their features. You will also learn about GraphQL NodeJS MongoDB connection, and how to do it with relevant code snippets and examples.

Simplify MongoDB’s ETL & Data Analysis with Hevo’s No-code Data Pipeline

Hevo Data, a No-code Data Pipeline, helps load data from any data source such as Databases, SaaS applications, Cloud Storage, SDK,s, and Streaming Services and simplifies the ETL process.

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled securely and consistently with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.

Simplify your Data Analysis with Hevo today! 

Get Started with Hevo for Free

What is GraphQL?

GraphQL NodeJS MongoDB Connection: Graphql logo

Facebook designed the GraphQL query language. It’s an alternative to REST. So, if you’re used to REST, keep in mind that GraphQL is a little different. It only has one endpoint for all requests, and the method must be a post request. GraphQL uses types and fields, and it’s extremely powerful because it gives all or just the data that’s required.

Most modern apps require data to be retrieved from a server and stored in a database. The API should provide an interface to the stored data that meets the needs of the application.

GraphQL is frequently misunderstood as a database technology. This is a common misunderstanding: GraphQL is an API query language, not a database query language. In that respect, it is database agnostic and may be utilized efficiently in any situation where an API is used.

GraphQL is a more efficient alternative to REST. REST is a popular method of exposing data from a server. Client applications were rather simple when the REST concept was invented, and development speed was not quite as fast as it is now. As a result, REST was a suitable fit for many applications. However, the API environment has shifted dramatically in recent years. Three elements, in particular, particular have posed a challenge to the way APIs are designed:

  • Mobile usage has increased drastically and this demands more efficient data loading.
  • There are many different varieties of frontend frameworks and platforms.
  • Continuous development and faster development are expected. 

GraphQL was created in response to the demand for greater flexibility and efficiency! It eliminates many of the flaws and inefficiencies that developers have when working with REST APIs.

What is Express for NodeJS?

GraphQL NodeJS MongoDB Connection: NodeJS Express logo

Express is a NodeJS web application framework that offers a comprehensive collection of functionality for building web and mobile applications. It makes it easier to create Node-based Web apps quickly. 

Express.js is built on the connect Node.js middleware module, which leverages the HTTP module. As a result, any connect-based middleware will function with Express.js. Some of the core features of the Express framework are listed below.

Features of ExpressJS:

  • Allows setting up of middlewares to respond to HTTP Requests.
  • Defines a routing table for doing various actions based on HTTP Method and URL.
  • Allows you to render HTML pages dynamically by supplying variables to templates.

What is MongoDB?

GraphQL NodeJS MongoDB Connection: MongoDB logo

MongoDB is a NoSQL database that stores data in BSON (Binary JSON) documents, each of which is based on a key-value pair structure. MongoDB’s ability to store schemaless data makes it ideal for capturing data with unknown structures. This documented-oriented approach is intended to provide a richer programming experience using modern programming techniques.

Key Features of MongoDB:

  • High-Performance: Data operations are fast and efficient due to their NoSQL nature.
  • Scalability: The data can be distributed across multiple machines equally and free of bulkiness. It can handle growing amounts of data comfortably.
  • Availability: Data is easily available as multiple copies are made and sent to other servers so even if one fails, the data can be found elsewhere.
  • Flexibility: MongoDB can be easily combined with other SQL and NoSQL databases.

Understanding GraphQL NodeJS MongoDB Connection Steps

Now, you will see how to connect GraphQL NodeJS MongoDB in a step by step process:

GraphQL NodeJS MongoDB Connection: Setting Up the Project

  • Step 1: Create a new project folder and initialize it using:
npm init
  • Step 2: Install Express middleware, express-graphql, and Graphql modules.
npm install express express-graphql graphql --save
  • Step 3: Create an app.js file. Use the code below and create your express server: 

const express = require('express');
 
 
const graphqlHTTP = require('express-graphql');
 
const schema = require('./schema/schema')
 

 
 
const app = express();
 

 
 
//This route will be used as an endpoint to interact with Graphql,
 
//All queries will go through this route.
 
app.use('/graphql', graphqlHTTP({
 
   //directing express-graphql to use this schema to map out the graph
 
   schema,
 
   //directing express-graphql to use graphiql when goto '/graphql' address in the browser
 
   //which provides an interface to make GraphQl queries
 
   graphiql:true
 
}));
 

 
 
app.listen(3000, () => {
 
   console.log('Listening on port 3000');
 
});

  • Step 4: You need to create a GraphQL schema. Create a new file schema.js inside the folder schema and define the schema as follows:

const graphql = require('graphql');

 
const { GraphQLObjectType, GraphQLString,
      GraphQLID, GraphQLInt, GraphQLSchema } = graphql;

 
//Schema defines data on the Graph like object types(book type), the relation between
//these object types and describes how they can reach into the graph to interact with
//the data to retrieve or mutate the data  

 
var fakeBookDatabase = [
   { name:"Book 1", pages:432 , id:1},
   { name: "Book 2", pages: 32, id: 2},
   { name: "Book 3", pages: 532, id: 3 }
]

 
const BookType = new GraphQLObjectType({
   name: 'Book',
   fields: () => ({
       id: { type: GraphQLID  },
       name: { type: GraphQLString },
       pages: { type: GraphQLInt }
   })
});

 
//RootQuery describes how users can use the graph and grab data.
//E.g Root query to get all authors, get all books, get a particular book
//or get a particular author.
const RootQuery = new GraphQLObjectType({
   name: 'RootQueryType',
   fields: {
       book: {
           type: BookType,
           //argument passed by the user while making the query
           args: { id: { type: GraphQLID } },
           resolve(parent, args) {
               //Here we define how to get data from a database source

 
               //this will return the book with id passed in argument by the user
               return fakeBookDatabase.find((item) => { return item.id == args.id});
           }
       }
   }
});
 
//Creating a new GraphQL Schema, with options query which defines query
//we will allow users to use it when they are making requests.
module.exports = new GraphQLSchema({
   query: RootQuery
});

Your data source is now defined in “fakeBookDatabase array”. You can use this array to fetch data from GraphQL and later on add the MongoDB database.

Schema mainly serves three purposes:

  • Defines data on the Graph like objects, such as BookType.
  • Specifies the relationship between these object kinds.
  • Describes how to interact with data in the graph, such as retrieving or changing it.
  • Step 5: Run your express server by running:
 node app.js 

Go to http://localhost:3000/graphql. Now your graphql client should be running.

  • Step 6: Run a query:-
{
 book(id:"1"){
    id
    name
    pages
 }
}

GraphQL NodeJS MongoDB Connection: Connecting Express to MongoDB Database

Your next GraphQL NodeJS MongoDB Connection step will be to connect your application to a database. In this case, connect to MongoDB. 

  • Step 1: Install mongoose.
npm install mongoose --save
  • Step 2: In the app.js file of your express application add the following code. This is to add Mongoose middleware and connect it to the MongoDB database.

const mongoose = require('mongoose');
 
mongoose.connect('MongoDB://<dbuser>:<dbpassword>@<MongoDB URI>')
 
mongoose.connection.once('open', () => {
 
   console.log('connected to database');
 
});
  • Step 3: Replace <dbuser> , <MongoDB URI> and <dbpassword> with your own credentials.  On running the application now, it should log ‘connected to database’.

GraphQL NodeJS MongoDB Connection: Define Mongoose Schema and Compile Them to Models

The next step in GraphQL NodeJS MongoDB Connection is to create a schema for your MongoDB database. Two schemas are needed – author and book. Create a new folder model in the project folder. Use the following GraphQL NodeJS MongoDB Connection code in the respective files – author.js and book.js.

  • Step 1: Author model schema:
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const authorSchema = new Schema({

   name: String,

   age: Number

});

module.exports = mongoose.model('Author', authorSchema);

  • Step 2: Book model schema:
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const bookSchema = new Schema({

   name: String,

   pages: Number,

   authorID: String

});

module.exports = mongoose.model('Book', bookSchema);

GraphQL NodeJS MongoDB Connection: Updating GraphQL Schema to Fetch data from Mlab Database

The next step in GraphQL NodeJS MongoDB Connection is to remove the dummy database and add the author model. Then make the required changes in RootQuery by adding extra fields books, authors, and make changes to the existing field book. Import the mongoose models.

const graphql = require('graphql');
const Book = require('../models/book');
const Author = require('../models/Author');

const {
   GraphQLObjectType, GraphQLString,
   GraphQLID, GraphQLInt,GraphQLSchema,
   GraphQLList,GraphQLNonNull
} = graphql;


//Schema defines data on the Graph like object types(book type), the relation between
//these object types and describes how they can reach into the graph to interact with
//the data to retrieve or mutate the data  


const BookType = new GraphQLObjectType({
   name: 'Book',
   //We are wrapping fields in the function as we don’t want to execute this until
   //everything is inilized. For example below code will throw an error AuthorType not
   //found if not wrapped in a function
   fields: () => ({
       id: { type: GraphQLID  },
       name: { type: GraphQLString },
       pages: { type: GraphQLInt },
       author: {
       type: AuthorType,
       resolve(parent, args) {
           return Author.findById(parent.authorID);
       }
   }
   })
});



const AuthorType = new GraphQLObjectType({
   name: 'Author',
   fields: () => ({
       id: { type: GraphQLID },
       name: { type: GraphQLString },
       age: { type: GraphQLInt },
       book:{
           type: new GraphQLList(BookType),
           resolve(parent,args){
               return Book.find({ authorID: parent.id });
           }
       }
   })
})



//RootQuery describes how users can use the graph and grab data.
//E.g Root query to get all authors, get all books, get a particular
//book or get a particular author.
const RootQuery = new GraphQLObjectType({
   name: 'RootQueryType',
   fields: {
       book: {
           type: BookType,
           //argument passed by the user while making the query
           args: { id: { type: GraphQLID } },
           resolve(parent, args) {
               //Here we define how to get data from a database source



               //this will return the book with id passed in argument
               //by the user
               return Book.findById(args.id);
           }
       },
       books:{
           type: new GraphQLList(BookType),
           resolve(parent, args) {
               return Book.find({});
           }
       },
       author:{
           type: AuthorType,
           args: { id: { type: GraphQLID } },
           resolve(parent, args) {
               return Author.findById(args.id);
           }
       },
       authors:{
           type: new GraphQLList(AuthorType),
           resolve(parent, args) {
               return Author.find({});
           }
       }
   }
});

//Creating a new GraphQL Schema, with options query which defines query
//we will allow users to use it when they are making requestsuntil.
module.exports = new GraphQLSchema({
   query: RootQuery
});

GraphQL NodeJS MongoDB Connection: Adding GraphQL Mutation

Mutation helps the user to add/update the database. We use mutations to edit server-side data, whereas queries are used to fetch data. If queries are the GraphQL counterpart of REST GET requests, mutations are the REST state-changing methods (like DELETE, PUT, PATCH, etc). Define the constant Mutation and add it as an option while exporting GraphQL schema for the GraphQL NodeJS MongoDB connection.

const graphql = require('graphql');
const Book = require('../models/book');
const Author = require('../models/Author');



const {
   GraphQLObjectType, GraphQLString,
   GraphQLID, GraphQLInt,GraphQLSchema,
   GraphQLList,GraphQLNonNull
} = graphql;



//Schema defines data on the Graph like object types(book type), relation between
//these object types and describes how it can reach into the graph to interact with
//the data to retrieve or mutate the data  



const BookType = new GraphQLObjectType({
   name: 'Book',
   //We are wrapping fields in the function as we dont want to execute this ultil
   //everything is inilized. For example below code will throw an error AuthorType not
   //found if not wrapped in a function
   fields: () => ({
       id: { type: GraphQLID  },
       name: { type: GraphQLString },
       pages: { type: GraphQLInt },
       author: {
       type: AuthorType,
       resolve(parent, args) {
           return Author.findById(parent.authorID);
       }
   }
   })
});



const AuthorType = new GraphQLObjectType({
   name: 'Author',
   fields: () => ({
       id: { type: GraphQLID },
       name: { type: GraphQLString },
       age: { type: GraphQLInt },
       book:{
           type: new GraphQLList(BookType),
           resolve(parent,args){
               return Book.find({ authorID: parent.id });
           }
       }
   })
})



//RootQuery describe how users can use the graph and grab data.
//E.g Root query to get all authors, get all books, get a particular
//book or get a particular author.
const RootQuery = new GraphQLObjectType({
   name: 'RootQueryType',
   fields: {
       book: {
           type: BookType,
           //argument passed by the user while making the query
           args: { id: { type: GraphQLID } },
           resolve(parent, args) {
               //Here we define how to get data from database source



               //this will return the book with id passed in argument
               //by the user
               return Book.findById(args.id);
           }
       },
       books:{
           type: new GraphQLList(BookType),
           resolve(parent, args) {
               return Book.find({});
           }
       },
       author:{
           type: AuthorType,
           args: { id: { type: GraphQLID } },
           resolve(parent, args) {
               return Author.findById(args.id);
           }
       },
       authors:{
           type: new GraphQLList(AuthorType),
           resolve(parent, args) {
               return Author.find({});
           }
       }
   }
});


//Very similar to RootQuery helps users to add/update to the database.
const Mutation = new GraphQLObjectType({
   name: 'Mutation',
   fields: {
       addAuthor: {
           type: AuthorType,
           args: {
               //GraphQLNonNull make these fields required
               name: { type: new GraphQLNonNull(GraphQLString) },
               age: { type: new GraphQLNonNull(GraphQLInt) }
           },
           resolve(parent, args) {
               let author = new Author({
                   name: args.name,
                   age: args.age
               });
               return author.save();
           }
       },
       addBook:{
           type:BookType,
           args:{
               name: { type: new GraphQLNonNull(GraphQLString)},
               pages: { type: new GraphQLNonNull(GraphQLInt)},
               authorID: { type: new GraphQLNonNull(GraphQLID)}
           },
           resolve(parent,args){
               let book = new Book({
                   name:args.name,
                   pages:args.pages,
                   authorID:args.authorID
               })
               return book.save()
           }
       }
   }
});



//Creating a new GraphQL Schema, with options query which defines query
//we will allow users to use when they are making requests.
module.exports = new GraphQLSchema({
   query: RootQuery,
   Mutation: Mutation
});

Now, you will be able to run these queries:

  • Adding an author.
GraphQL NodeJS MongoDB Connection:  Adding an author
  • Adding a book.
GraphQL NodeJS MongoDB Connection:  Adding a book
  • Getting a book with an ID.
GraphQL NodeJS MongoDB Connection:  Getting book with ID
  • Getting all the books.
GraphQL NodeJS MongoDB Connection:  Getting all the books
  • Getting all the authors.
GraphQL NodeJS MongoDB Connection:  Getting all the authors

Conclusion

The GraphQL Nodejs MongoDB connection has been established successfully. This article dived deep into how to perform the GraphQL Nodejs MongoDB connection with detailed steps and code snippets. After following this guide, you would have successfully connected GraphQL NodeJS MongoDB and you can now perform queries on them.

As a Developer, extracting complex data from a diverse set of data sources like Databases, CRMs, Project management Tools, Streaming Services, Marketing Platforms to your MongoDB Database can seem to be quite challenging. If you are from non-technical background or are new in the game of data warehouse and analytics, Hevo Data can help!

Hevo Data will automate your data transfer process, hence allowing you to focus on other aspects of your business like Analytics, Customer Management, etc. This platform allows you to transfer data from 150+ multiple sources to Cloud-based Data Warehouses like Snowflake, Google BigQuery, Amazon Redshift, etc. It will provide you with a hassle-free experience and make your work life much easier.

Try Hevo’s 14-day free trial and experience the feature-rich Hevo suite first hand. You may also have a look at the amazing price, which will assist you in selecting the best plan for your requirements.

FAQs

How to use GraphQL in Node js with MongoDB?

To use GraphQL in a Node.js application with MongoDB, follow these steps:
– Set Up your Node JS Environment
– Create MongoDB Connection
– Define in Mongoose Model
– Set Up your GraphQL Schema
– Set Up Express server for GraphQL
– Run your Server

Is MongoDB good for GraphQL?

MongoDB can be a good choice for GraphQL for several reasons:
– Flexibility
– Scalability
– JSON-Like Documents
– Aggregation Framework

Does GraphQL use NodeJS?

independent of any specific programming language or environment. However, it is commonly used with Node.js due to the popularity of JavaScript for building APIs. The graphql and express-graphql libraries are examples of how GraphQL can be implemented in a Node.js environment.

Sharon Rithika
Content Writer, Hevo Data

Sharon is a data science enthusiast with a hands-on approach to data integration and infrastructure. She leverages her technical background in computer science and her experience as a Marketing Content Analyst at Hevo Data to create informative content that bridges the gap between technical concepts and practical applications. Sharon's passion lies in using data to solve real-world problems and empower others with data literacy.