Introduction
In this article we will learn about how we can connect mongodb to our next.js project.
I am assuming you know how to setup next.js Project
We will be using mongodb atlas for the database
use
npm i mongoose
to install which is a Object Data Modeling (ODM) library for MongoDB
Get Started
Using mongodb database in next.js is quite similar to using it with express. However there are some key difference as next.js runs on edge.
Start with creating a folder name lib in your
src
directory.Then create a file with name of your choice, here we named is
dbConnect.ts.
you can also use dbConnect.js if you are working with JavaScript.
Your folder structure should look like this:-
What's inside dbConnect.ts?
import mongoose from "mongoose"; type ConnectionObject = { isConnected?:number } const connection : ConnectionObject = { }
first we import mongoose from mongoose.
we also created a connection object which is a an empty object initially.
After that we connect our mongodb atlas database.
Main Function
async function dbConnect(): Promise<void> { if(connection.isConnected){ console.log("Already connected to database") return } try { const db = await mongoose.connect(process.env.MONGODB_URI || '',{}) connection.isConnected = db.connections[0].readyState console.log("DB Connected Successfully") } catch (error) { console.log("Database connection failed"); console.log(error); process.exit() } } export default dbConnect;
We are creating a dbConnect function and exporting it to use anywhere to connect to database.
we try await
mongoose.connect(process.env.MONGODB_URI || '',{})
to connect to our database.MONGODB_URI is simply your mongodb connection URL you can get it from the project you created on mongodb atlas
If we successfully connected to the database we first provide value to
connection.isConnected
we created which was initially set to empty object.
and if we fail to connect we throw error.
How To Use
Just called dbConnect function in the api route
import dbConnect from "@/lib/dbConnect"; export async function GET(request:Request){ await dbConnect() //remiaining code }
Point to Understand
Main thing we needs to understand while connecting mongodb or any database with your next.js project that is next.js runs on edge. You can learn about edge computing in this blog
In short you have to connect to database every time you tried to hit any api endpoint.
Sometimes the connections to database is already exist and sometimes we have to connect to database again. That's why we created connection object
const connection : ConnectionObject = { }
when we connection to database we set connection to the state of database.
then after some time if we hit any api endpoint first we check if we already connected to database through connection object if not then establish connection with database again.