Table of contents
In the ever-evolving landscape of backend development, MongoDB stands tall as a NoSQL database solution, offering flexibility and scalability. In this guide, we'll walk through the step-by-step process of integrating MongoDB into a Node.js GraphQL API, unlocking the potential for robust data storage and retrieval.
Why MongoDB?
MongoDB, a star in the database galaxy, is a NoSQL solution known for its flexibility and scalability. Unlike traditional relational databases, MongoDB stores data in a document-oriented format, offering agility in handling complex and evolving data structures.
Key Advantages of MongoDB
Flexible Schema: MongoDB's dynamic schema allows for easy adaptation to changing data requirements.
Horizontal Scalability: Effortlessly scale your database horizontally by adding more servers, ensuring optimal performance.
Document-Oriented: Data is stored in flexible, JSON-like BSON documents, making it easy to work with and accommodating complex structures.
Support for Various Data Types: MongoDB supports a diverse range of data types from text to geospatial information.
High Performance: Indexing and querying capabilities contribute to swift and efficient data retrieval.
Aggregation Framework: Perform advanced analytics and transformations within the database using MongoDB's powerful aggregation framework.
Automatic Sharding: MongoDB's built-in sharding ensures even data distribution across clusters for improved scalability.
5 Steps to add MongoDB in our graphql API
Setting Up the Node.js GraphQL API
Integrating MongoDB with Mongoose
Defining Mongoose Models
Implementing GraphQL Resolver
Leveraging MongoDB in GraphQL Resolvers
Let's discuss and start implementing each step
Setting Up the Node.js GraphQL API
We are not going into much detail about setting up the graphql API here. Here is the link to the article ( Setup Node.js GraphQL API ) and here is the GitHub repository link of an already set API GitHub repository.
Integrating MongoDB with Mongoose
- Install the Mongoose library to our project
npm install mongoose --save # install the mongoose library
- Connect the database to the node.js application
// connect the mongodb database
// Database URL from atlas cloud or local database URL
const DATABASE_URL: string = `mongodb://localhost:27017/test`
mongoose.connect(DATABASE_URL)
.then(() => {
console.log('Database connected successfully')
})
.catch((e: any) => {
console.log('Error connecting : ', e?.message)
})
We connected the database after we successfully started the application in this example. You can choose when and where you want to connect to a database to your application based on your needs.
Here is the output of this step :
Defining Mongoose Models
There are 2 steps in defining the Mongoose model
Defining the schema: Defines the shape of the documents
Defining the model: Models are responsible for creating and reading documents from the underlying MongoDB database
import mongoose, {Schema} from 'mongoose';
// defining post schema
const postSchema = new Schema({
title:String,
content:String
});
// defining post model
const Post = mongoose.model("Post", postSchema);
export default Post;
The postSchema variable defines the structure of post documents, comprising title and content fields, both of type String. Subsequently, the Post model is created using mongoose.model(), associating it with the "Post" collection and the postSchema schema. Finally, the Post model is exported for use in other modules, enabling seamless interaction with a MongoDB database and facilitating CRUD operations on posts.
Implementing GraphQL Resolver
We already know how to define and implement the graphql resolver. If you need a recap you can read this article ( GraphQL Resolvers )
Leveraging MongoDB in GraphQL Resolvers
Now we have all the necessary setup done to use database connectivity in our resolvers. let's understand the usage of MongoDB in our graphql API by implementing 2 resolvers
Creating a post in our database
Fetching all the posts from our database
Create a post in MongoDB
createPost: async (_parent: any, args: any, _context: any) => {
// create new post document
const post = new Post(args);
//save post document and return the saved document
return await post.save();
}
createPost resolver receives three parameters: _parent
, args
, and _context
. Using the args
parameter, it creates a new post document based on the data provided. Then, it saves the post document to the database using the save()
method and returns the saved document.
Output :
Fetch Posts from the database
posts: async () => {
// fetch all posts from database via Post model
return await Post.find();
}
This GraphQL resolver retrieves all posts from the database by querying the Post model. Using the find()
method, it retrieves all post documents stored in the database and returns them to the GraphQL client.
Output :
MongoDB proves to be a dynamic force in the realm of backend development. Its flexible schema, horizontal scalability, and document-oriented nature make it a prime choice for applications demanding adaptability and performance. With support for diverse data types, high-performance capabilities, and advanced features like automatic sharding, MongoDB stands as a reliable ally in crafting robust and scalable Node.js GraphQL APIs. As you embark on your journey with MongoDB, the possibilities for seamless data storage and retrieval are boundless.
Happy coding! ๐๐๐ป
Here is the link to our GitHub repository - GraphQL with MongoDB