How to Connect MongoDB Database in Next.js 14 with Mongoose: A Simple Guide

Do you want to use MongoDB, a popular NoSQL database, with your Next.js 14 app? Let’s do it together using Mongoose, a tool for making MongoDB easier to work with in Node.js. Here’s a step-by-step guide to help you through the process:

Before We Start

First, make sure you have Node.js installed on your computer. You’ll also need MongoDB either installed locally or accessible through MongoDB Atlas, a cloud-based solution.

Step 1: Create a Next.js App

Open your terminal and run these commands to create a new Next.js app and navigate into its directory:

npx create-next-app your-app-name
cd your-app-name

Step 2: Install Mongoose

In your project directory, install Mongoose, which helps us connect to MongoDB easily:

npm install mongoose

or

yarn add mongoose

Step 3: Setting Up MongoDB Connection with Mongoose

Create a new file in the lib directory of your Next.js project. You can name it mongoose.js or connectDB.js. Here’s a simple way to connect:

import mongoose from "mongoose";

export default async function connect(){
    try {
        mongoose.connect(process.env.MONGO_URL)
        const connection = mongoose.connection
        connection.on('connected',()=>{
            console.log("Mongo Db Connected");
        })
        connection.on('error',(err)=>{
            console.log("Mongo Db Connection error, Please Make sure db is up and running" + err);
            process.exit()
        })
    } catch (error) {
        console.log("Database connection failed");
        console.log(error);
    }
}

Replace 'process.env.MONGO_URL' with your MongoDB connection string. You can keep it in an environment variable or a .env file.

Step 4: Create A User Schema In Models folder

import mongoose from "mongoose";

const userSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true,
        unique:true
    },
    username:{
        type:String,
        required:true,
        unique:true
    },
    password:{
        type:String,
        required:true
    },

})

const User = mongoose.models.Myuser || mongoose.model("Myuser",userSchema)
export default User

Step 5: Using the Database Connection

Let’s create an API route to fetch data from our MongoDB collection. In the src/app/api/users/ directory, create a new file named route.js:

import { NextResponse } from "next/server";
import connect from "@/lib/connectDB";
import User from "@/models/userModel"; // Assume you have a UserModel
connect();

export async function GET(req) {
    const data = await User.find()
    return NextResponse.json({ "data": data })
}

Step 6: Running Your Next.js App

Now, run your Next.js app with the following command:

npm run dev

or

yarn dev

Step 7: Testing the API Route

Once your app is running, test the API route we created earlier. Use your browser or a tool like Postman to send a GET request to http://localhost:3000/api/users/. You should see the data fetched from your MongoDB collection in JSON format.

Conclusion

You’ve successfully connected your Next.js 14 app to a MongoDB database using Mongoose! Now you can explore more features and build powerful applications with Next.js and MongoDB.

Feel free to dive deeper into CRUD operations, authentication, and data validation to enhance your app even further.

That’s it for this guide. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *