In this blog, we are going to learn about the MongoDB database. And how one can establish a connection between the Next JS application and the MongoDB database.
Let's start with learning and coding the MongoDB connection in Next JS App.
Understanding Of MongoDB Database
MongoDB is a popular open-source, document-oriented NoSQL database that uses a flexible, JSON-like data model. It stores data in collections of documents, which can have nested fields and arrays, making it a highly flexible database that can handle a wide range of data types and structures. MongoDB is designed to be highly scalable and can handle large amounts of data across multiple servers. It also includes features like auto-sharding and horizontal scaling, which make it suitable for large-scale, high-traffic applications. MongoDB is commonly used for web applications, content management systems, and real-time analytics, among other use cases.
Create a Next JS App
npx create-next-app b-05-mongodb-connection
Create a Database Folder
Once project files are created, we can go inside the project directory and create a "database" folder in the below hierarchy -> "/backend/config/database".
Create a ".env" File
We create a ".env.development" file inside the project directory.
Installing Required Libraries
Installing the "mongoose" library.
npm i mongoose
Coding MongoDB Connection
we will follow the below steps for establishing a MongoDB database connection-
We will use MongoDB Atlas as a database, which is an online database provided by MongoDB. We will make an account on the MongoDB atlas and create a cluster in it. We will use the MongoDB connection URI provided by MongoDB Atlas to establish a connection with the MongoDB cluster. I assumed that you already have the MongoDB connection URI or please create one and save it in notepad for future use. Please comment on this blog, if you need to know the steps for creating a cluster on MongoDB atlas.
And in that ".env.development" file, we provide a variable "MONGODB_URI" and assign our MONGODB_URI link which we saved in the notepad.
We create a file name "dbConnection.js" in the "/backend/config/database" folder.
We write the below code in the "dbConnection.js" file.
import mongoose from "mongoose"; const MONGODB_URI = process.env.MONGODB_URI; const connectMongo = async () => { try { const { connection } = await mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, }); if (connection.readyState == 1) { console.log( "MongoDB Database connection status -> Application connected with MongoDB Database" ); return connection; } } catch (errors) { console.log(errors.message); } }; export default connectMongo;
Run the Server in Dev Mode
We run the below command in the project directory and the application will start running in dev mode on "localhost:3000".
npm run dev
Testing the MongoDB Connection
When we create a new project there is a file "hello.js" inside the "/pages/api" folder. It is a default backend route file. We will use this file for testing our MongoDB connection.
We will update the "hello.js" file as below -
import connectMongo from "@/backend/config/database/dbConnection";
export default async function handler(req, res) {
await connectMongo();
res.status(200).json({ name: "John Doe" });
}
We hit the URL: "http://localhost:3000/api/hello" on the chrome browser.
We get the below response -
And when we see our application terminal window, we will see the connection status of the MongoDB, logged in the terminal.
Finishing Up
Thank you for reading my article! I hope this has given you some insight into how to establish the connection between the Next JS App and the MongoDB database.