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.
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.
Let's discuss and start implementing each step
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.
1. Install the Mongoose library to our project
npm install mongoose --save # install the mongoose library
2. 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 :
There are 2 steps in defining the Mongoose model
1. Defining the schema: Defines the shape of the documents
2. 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.
We already know how to define and implement the graphql resolver. If you need a recap you can read this article ( 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
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 :
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