Connecting Your Next.js Project to MongoDB Atlas Using Mongoose: A Step-by-Step Guide.

Nithish Reddy
4 min readSep 5, 2023

--

Step 1: Begin by setting up a Next.js project using either

npx create-next-app@latest or yarn create next-app with the default installation.

Step 2: Next, install the Mongoose library using the npm command

npm install mongoose.

Step 3: Log in to your MongoDB Atlas account and copy the connection string, which can be found under “Connect” > “Connecting with MongoDB for VS Code.” You will also need to note the password, which can be located under “Security” > “Database Access.”

Step 4: Create a .env file within your Next.js project and paste the provided code, replacing the placeholders with your actual MongoDB connection string, username, password, and databaseName desired database name.

 DATABASE_URL = mongodb+srv://username:password@package.2uykwnp.mongodb.net/databaseName?retryWrites=true&w=majority

Step 5: Inside your project, create a lib folder within the pages directory. In this lib folder, create a file named connectDB.js.

Step 6: Insert the provided code into the connectDB.js file.

import mongoose from "mongoose";

const DATABASE_URL = process.env.DATABASE_URL;

if (!DATABASE_URL) {
throw new Error("Please define the DATABASE_URL environment variable inside .env.local");
}

let cached = global.mongoose;

if (!cached) {
cached = global.mongoose = { conn: null, promise: null };
}

async function connectDB() {
if (cached.conn) {
return cached.conn;
}

if (!cached.promise) {
const opts = {
bufferCommands: false,
};

cached.promise = mongoose.connect(DATABASE_URL, opts).then((mongoose) => {
return mongoose;
});
}
cached.conn = await cached.promise;
return cached.conn;
}

export default connectDB;

Step 7: Now, outside of the pages directory, create a folder named Model to store all your schemas. Within the Model folder, create a file named User.js.

Step 8: Copy and paste the provided code into the User.js file, and feel free to customize it as needed.

import mongoose from "mongoose";

const User = mongoose.Schema(
{
name: String,
age:Number
},
{
timestamps: true,
}
);

export default mongoose.models.User || mongoose.model("User", User);

Restart the Server

Step 9: In the pages directory, specifically in the index.js file, create a form that allows users to input their details for storage.

import Head from 'next/head'


export default function Home() {
return (
<div>

<form action="./api/data" method="post">

<label htmlFor="name">Enter Name </label>
<input type="text" name="name" id="name" />


<label htmlFor="age"> Enter Age </label>
<input type="text" name="age" id="age" />

<input type="submit" value="submit" />

</form>
</div>
)
}

Step 10: Within the pages directory, create a folder named api, and in this folder, create a file named data.js.

Step 11: Insert the provided code into the data.js file. This code will handle the connection to MongoDB, and when users enter data and submit the form, a new user will be created in the database.

import user from "../../Model/user";
import connectDB from "../lib/connectDB"

export default async function handler(req, res) {
await connectDB()

const {name , age } = req.body;
const person = new user({
name:name,
age:age
})
await person.save()
console.log("inside api",name , age)
res.status(200).json({ done: true })
}

This step-by-step guide demonstrates how to set up a Next.js project, connect it to MongoDB Atlas using Mongoose, and create a basic form to store user data in the database. Following these steps should help you establish a functional database connection within your Next.js application.

Thank You…

--

--