Integrating MongoDB with a Next.js application is a powerful way to create dynamic, data-driven websites and applications.
This article will guide you through the process of setting up MongoDB (using Mongoose as the ORM) to interact with your database. We’ll use MongoDB Atlas to store our data on the cloud, then display the data in a Next.js application using the app router.
There are several other ways you can achieve this. Chief amongst them is server actions with an ORM like Prisma or Drizzle. This guide will focus on doing things in the good old way we set up an Express application to integrate with a React or HTML/JavaScript project using MongoDB as the database and Mongoose as the ORM.
Before we dive into the process, here are a few things you should already know and have in place:
A MongoDB Atlas account
Basics of Next.js
Basic understanding of mongoose
Set up the MongoDB Atlas Project
Since we’ll fetch the data from a MongoDB Atlas database, let’s set up the database first.
Step 1: Log in to MongoDB Atlas
Log on to mongodb.com and log in to your account, or create an account if you don’t have one.
Step 2: Create an Atlas Project
When you’re in, click on the folder icon on the top-right corner and then the New Project button.
In the next window, give your project a name and click the Next button
Click Create Project on the next page and you’ll be prompted to create a cluster.
Step 3: Create a Cluster
A cluster is the server that will store your data. So, you need one.
Click the giant Create button to start the process
Select the MO free tier, name your cluster, and click the Create Deployment button.
As your database grows, you might need to upgrade to any of the generous free tier
Step 4: Connect to your Database
After creating your cluster, you’ll be prompted to connect to it. But first, you need to create a database user.
Enter the username and password for the database user and click the Create Database User button.
After that, the Choose a connection method button will turn green, so click it.
Select drivers in the next pop-up
After that, make sure Node JS is selected and copy the connection string, then click Done
Step 5: Create Database Network Access
By default, the current IP address of your computer will only be able to access the database. You can temporarily allow access from anywhere, and then later change that based on where your app is deployed to.
To do that, select Network Access from the sidebar and click ADD IP ADDRESS
In the popup that shows up after that, click ALLOW ACCESS FROM ANYWHERE and Confirm
Step 6: Add Data to your Database
The next thing to do is add the data to query to your database.
Click Database in the sidebar and then Browser Collections
Select Add My Own Data
You will then be prompted to create a database. Give your database a name (I chose fav-animals), and your collection a name (I chose animals), then click the Create button.
When you do that, you’ll be directed to an interface that looks like the one you can see below:
Click the INSERT DOCUMENT button
Remove the existing fields and select the curly braces
Expand the JSON data below and paste it in:
Afer you’ve pasted in the data, if any of the values are greyish, it means there are errors. Make sure all the values are green and you’ll be good to go.
Click Insert
Install Next.js to Start Setting Up MongoDB in a Next.js App
Now that you’re done with setting up MongoDB Atlas and filling the database with data, the next thing is to install Next.js.
Create a folder and open it with VS Code, then open the integrated terminal and run the command below:
The installation wizard will ask you a few questions. Here are the choices I made:
When the installation is done, run npm run dev to start the local dev server of the application.
Install MongoDB and Mongoose Packages
We need the Mongoose ORM and MongoDB library to effectively connect to our database and set up both our model and route. So in the terminal again, run the command below:
Create Database Connection File
Create a config folder in the root. Inside the folder, create a database.ts file and paste the following in it:
What goes in the mongoose.connect() method is the connection string you copied in step 4.
So, create a .env file in the root, create a MONGODB_CONNECTION_URI variabel and assign the connection string to it. Make sure you replace the password with your database user password.
Also, enter the name of your database as the database to use. Otherwise, MongoDB will automatically create a test database for you.
The MONGODB_CONNECTION_URI variable should look like this:
To quickly test the connection, go to page.tsx inside the app folder. Inside the file, import the database connection file the log it to the console by invoking it:
If you see the text MongoDB connected successfully (or any console message you entered in the database connection file) in the console, then everything is working fine. Otherwise, look at the error message to figure out what could have gone wrong.
On many occasions, the connection can fail because of a wrong username and password. So make sure both are correctly entered.
Create the Database Model
The next thing is to create a model for the database. This model will define what we expect to get from the database, what we have to insert, and what we need to update. It’s like a validation for what we want in the database.
Create a models folder in the root and an Animal.ts file in it. After that, import Schema, model, models, and Document all from mongoose and define the types for the fields:
After that, define the schema corresponding to the interface. Expand the code below to see the full schema:
Create the API Route to Query the Data
Inside the app directory, create an api folder, then an animal folder, and then a route.ts file.
Inside that route.ts file, paste the following:
Query the Data
To finally query the data, head over to the page.jsx file and fetch the data from your local api route.
You can’t use a useState or useEffect hook to fetch data in a server component, so you can do the fetching directly:
Join my Free Newsletter
Subscribe to my newsletter for coding tips, videos from reputable sources, articles from OG tech authors, and a ton of other goodies.
No BS. No fluff. Just pure software development goodies on a Sunday every week.
Display the Data (Animals)
Finally, you can map through the favAnimals data and render them on the page. Expand the code below to see how I did it and styled the elements with Tailwind CSS:
If you try to see what’s going on in the browser, you’ll see this error:
To fix the error, add this to the nextConfig object inside the next.config.mjs file in the root:
Now you should see the animals rendered in the browser: