If you are using the GraphQL API and it does not connect to other systems, such as databases or third-party APIs, it is unlikely to be of much use. One of the most appealing aspects of GraphQL architecture is that introducing third-party connectors is both simple for the developer and completely transparent for the client.
Upon a complete walkthrough of this article, you will learn about GraphQL, how it is different from the REST approach and why has it created such buzz among the new-age developers. You will also learn about the steps required to build a GraphQL Express MongoDB Connection. Read along to learn more about the GraphQL Express MongoDB Integration!
Table of Contents
Prerequisites
- Basic understanding of APIs.
- Fundamental knowledge of Server-Side Programming.
What is GraphQL?
GraphQL is a Query Language and Server-Side Runtime for Application Programming Interfaces (APIs) that prioritizes providing clients with only the information they need. GraphQL, a REST alternative, allows developers to create requests that pull data from multiple data sources in a single API call. Furthermore, GraphQL allows API maintainers to add or remove fields without affecting existing queries. Developers can use a variety of methods they want to create APIs, and the GraphQL specification ensures that they work in predictable ways for clients.
Why do you need GraphQL?
Traditional REST API Calls do not offer the flexibility to request a customized set of data. GraphQL, on the other hand, allows clients to define the structure of the data required, and the same data structure is returned by the server. This prevents excessively large amounts of data from being returned. Furthermore, maintaining multiple endpoints in a REST architecture is difficult. As the application grows in size, the number of endpoints also increases whereas GraphQL APIs are more organized as they support structured types and schema fields while using a single API endpoint to request data. If you want to read/learn more about REST vs GraphQL you can check out this blog/article.
What is MongoDB?
MongoDB is a well-known Open-Source NoSQL Database written in C++. MongoDB is a Document-oriented Database that uses JSON-like documents with a Dynamic Schema to store data. It means that you can store your records without having to worry about the Data Structure, the Number of Fields, or the Types of Fields used to store values. Documents in MongoDB are similar to JSON Objects.
You can change the structure of records (which MongoDB refers to as Documents) by simply adding new fields or deleting existing ones. This feature of MongoDB allows you to easily represent Hierarchical Relationships, Store Arrays, and other complexes Data Structures. Nowadays, many tech giants, including Facebook, eBay, Adobe, and Google, use MongoDB to store colossal amounts of data.
Key Features of MongoDB
MongoDB offers a wide range of unique features that make it a better solution in comparison to other conventional databases. Some of these features are discussed below:
- Schema Less Database: A Schema-Less Database allows various types of Documents to be stored in a single Collection(the equivalent of a table). In other words, in the MongoDB Database, a single Collection can hold multiple Documents, each of which can have a different number of Fields, Content, and Size. It is not necessary for one document to be similar to another which is a prerequisite in Relational Databases. Due to this feature, MongoDB offers great flexibility to the users.
- Index-based Document: Each field in a MongoDB Database is indexed with Primary and Secondary Indices, which makes it easier to retrieve information from the pool of data.
- Scalability: Sharding in MongoDB allows for Horizontal Scalability. Sharding refers to the process of distributing data across multiple Servers. A large amount of data is partitioned into data chunks using the Shard Key, and these data chunks are evenly distributed across Shards that reside across many Physical Servers.
- Replication: MongoDB offers high availability of data by creating multiple data copies and sending these to a different server so that if one server fails, the data can still be retrieved from another Server.
Hevo Data is a No-code Data Pipeline that offers a fully managed solution to set up Data Integration from 100+ Data Sources (including 40+ Free sources) and will let you directly load data from sources like MongoDB to a Data Warehouse or the Destination of your choice. It will automate your data flow in minutes without writing any line of code. Its fault-tolerant architecture makes sure that your data is secure and consistent. Hevo provides you with a truly efficient and fully automated solution to manage data in real-time and always have analysis-ready data.
Get Started with Hevo for Free
Let’s look at some of the salient features of Hevo:
- Fully Managed: It requires no management and maintenance as Hevo is a fully automated platform.
- Data Transformation: It provides a simple interface to perfect, modify, and enrich the data you want to transfer.
- Real-Time: Hevo offers real-time data migration. So, your data is always ready for analysis.
- Schema Management: Hevo can automatically detect the schema of the incoming data and maps it to the destination schema.
- Connectors: Hevo supports 100+ Integrations to SaaS platforms FTP/SFTP, Files, Databases, BI tools, and Native REST API & Webhooks Connectors. It supports various destinations including Google BigQuery, Amazon Redshift, Snowflake, Firebolt, Data Warehouses; Amazon S3 Data Lakes; Databricks; MySQL, SQL Server, TokuDB, MongoDB, and PostgreSQL Databases to name a few.
- Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
- Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
- Live Monitoring: Advanced monitoring gives you a one-stop view to watch all the activities that occur within Data Pipelines.
- Live Support: Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
Sign up here for a 14-Day Free Trial!
How to Set up a GraphQL Express MongoDB Connection?
Image Source
By creating a connection between GraphQL and MongoDB, you can create Integrated Servers and APIs. Follow the steps given below to set up the GraphQL Express MongoDB Connection:
Step 1: Set up Express GraphQL
The first step involved in building GraphQL Express MongoDB Integration requires you to create a new project and set up Express GraphQL:
- Use the following npm command to initialize a new project:
$ npm init -y
- Now, install the necessary dependencies for Express, MongoDB (Mongoose), and some additional dependencies for Express’s functionality by using the following command:
$ npm install express mongoose body-parser cors --save
- Apollo Server is a community-maintained Open-Source GraphQL Server that works well with all Node.js HTTP Server Frameworks, so you should download and save it next. You can use the following command to do so:
$ npm install apollo-server-express --save
- Once you have successfully executed the above commands, you will see a package.json and a package-lock.json file within your specified directory.
Step 2: Launch the Express Server
Once you have successfully set up a production environment, you can start developing the Integrated Server and API by setting up GraphQL Express MongoDB Integration. Follow the steps given below to do so:
- Open the index.js file and paste the following piece of code into it. This will include all the necessary external modules present in separate files:
const express = require('express');
const mongoose = require('mongoose');
const schema = require('./schema');
const bodyParser = require('body-parser');
const cors = require('cors');
const { ApolloServer } = require('apollo-server-express');
- Now, use the following code to connect the required project to your MongoDB database. Also, do not forget to include an error message:
const url = "mongodb://localhost:27017/moviesdb";
const connect = mongoose.connect(url, { useNewUrlParser: true });
connect.then((db) => {
console.log('Connected correctly to server!');
}, (err) => {
console.log(err);
});
- Create a new Apollo Server with typeDefs and Resolvers.
const server = new ApolloServer({
typeDefs: schema.typeDefs,
resolvers: schema.resolvers
});
- It’s now time to launch the Express Server at port 4000. This will allow you to interact with what you are building in real-time.
const app = express();
app.use(bodyParser.json());
app.use('*', cors());
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`Server ready at
http://localhost:4000${server.graphqlPath}`));
Step 3: Create a Mongoose Model
- Let’s create a basic Movie API capable of performing all the CRUD (Create, Read, Update, Delete) operations on a Movie database. Create the file models/movie.js by using the following piece of code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const movieSchema = new Schema({
name: {
type: String,
required: true
},
rating: {
type: Number,
required: true
},
producer: {
type: String,
required: true
}
}, {
timestamps: true
});
var Movies = mongoose.model('Movie', movieSchema);
module.exports = {Movies, movieSchema};
- The above code basically determines the schema of the database that will contain the movies data. Every movie will have a String Name, a String Producer, and a Rating of type Number.
Step 4: Design the Schema
Now, let’s move on to the schema.js file, which will serve as the foundation for the GraphQL Express MongoDB Connection:
- Create a new file called schema.js in the root of the folder and add the following code to it:
const { gql } = require('apollo-server-express');
const Movie = require('./models/movie').Movies;
const typeDefs = gql `
type Movie {
id: ID!
name: String!
producer: String!
rating: Float!
}
type Query {
getMovies: [Movie]
getMovie(id: ID!): Movie
}
type Mutation {
addMovie(name: String!, producer: String!, rating: Float!): Movie
updateMovie(id: ID!, name: String!, producer: String!, rating: Float): Movie
deleteMovie(id: ID!): Movie
}
- Now, let us break down the above code into segments:
- The type Movie consists of an ID, the name of the film and its producer, and a rating of type Float. The “!” after the types indicates that these fields are required.
- GraphQL can create operations in a single endpoint, as compared to the REST approach of performing different tasks at different endpoint URLs. The type Query determines GET operations, and the type Mutation determines modification operations such as POST, DELETE, and so on.
- getMovies in the above code returns a list of all available movies present in the database, whereas getMovie, returns the specific movie by its ID.
- Now, you’ll connect GraphQL to the Mongoose Database queries by using Resolvers that will perform the database actions. Resolvers are a group of functions that connect schema fields and types to different backends. It can read, write, and delete data from and to any database. In a nutshell, Resolver serves as a GraphQL Query Handler. Here’s how you can incorporate Resolvers into the code:
const resolvers = {
Query: {
getMovies: (parent, args) => {
return Movie.find({});
},
getMovie: (parent, args) => {
return Movie.findById(args.id);
}
},
Mutation: {
addMovie: (parent, args) => {
let movie = new Movie({
name: args.name,
producer: args.producer,
rating: args.rating,
});
return movie.save();
},
updateMovie: (parent, args) => {
if (!args.id) return;
return Movie.findOneAndUpdate(
{
_id: args.id
},
{
$set: {
name: args.name,
producer: args.producer,
rating: args.rating,
}
}, {new: true}, (err, Movie) => {
if (err) {
console.log('Something went wrong when updating the movie');
} else {
continue;
}
}
);
}
}
}
module.exports = {typeDefs,resolvers};
Once you follow all the above steps in the correct sequence, you will be able to establish GraphQL Express MongoDB Connection in a seamless manner.
Conclusion
This article introduced you to GraphQL and MongoDB along with the salient features that they offer. Furthermore, it introduced you to the steps required to set up the GraphQL Express MongoDB Connection. As your business begins to grow, data is generated at an exponential rate across all of your company’s SaaS applications, Databases, and other sources. To meet this growing storage and computing needs of data, you would require to invest a portion of your engineering bandwidth to integrate data from all sources, Clean & Transform it, and finally load it to a Cloud Data Warehouse for further Business Analytics. All of these challenges can be efficiently handled by a Cloud-Based ETL tool such as Hevo Data.
Visit our Website to Explore Hevo
Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources like MongoDB and a wide variety of Desired Destinations, with a few clicks. Hevo Data with its strong integration with 100+ sources (including 40+ free sources) allows you to not only export data from your desired data sources & load it to the destination of your choice, but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.
Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.
Share with us your experience of learning about the GraphQL Express MongoDB Connection in the comments below!