Connect to MongoDB in NextJS with Mongoose

In this article, we will show you how to set up your database connection to MongoDB with a NextJS application.

Install Mongoose

We will be using Mongoose, which is an Object Data Modeling tool for MongoDB, which makes working with MongoDB really simple.

First, make sure you install it:

npm install mongoose

Creating a Database Connection Utility

Mongoose will create a global object that will let you connect to MongoDB if the connection exists.

To connect to the database, you have to do a check to make sure there isn't already a connection open:

import mongoose from "mongoose";

export const db = async () => {
  // I like to throw an error if the app doesn't get the right env variables
  if (!process.env.MONGODB_URI) {
    throw new Error("MONGODB_URI not provided");
  }

  try {
    // If readyState === 0 then there is no connection
    if (mongoose.connection.readyState === 0) {
      await mongoose.connect(process.env.MONGODB_URI);
      console.log("Connected to DB");
    }
  } catch (error) {
    console.log(error);
  }
};

This snippet checks to see if the readyState === 0, which would indicate there is no connection. We can then connect/reconnect to the database.

Create a Data Model

So our example is complete, let's create a simple User model so we can test our connection:

// models/user.js
import mongoose from "mongoose";

const urlSchema = new mongoose.Schema(
  {
    name: String,
    title: String
);
// This OR checks if the model has already been created rather than created each time. 
export const Url = mongoose.models.Url || mongoose.model("Url", urlSchema);

Using the Database Connection

In this example, we will create a simple API, route.js in our app folder. This API route will create a new user when you POST the data:

// app/user/route.js
import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { User } from "@/models/user";
import mongoose from "mongoose";

export async function POST(req) {
  try {
    // Incoming request contains the name and title
    const { name, title } = await req.json();
    await db(); // 👈 Connect to the database here
    const response = await User.create({ name, title });
    const { name, title } = response;
    return NextResponse.json({ name, title }, { status: 201 });
  } catch {
    return NextResponse.json(
      { error: "Internal Server Error" },
      { status: 500 }
    );
  }
}

And just like that, we are able to use our database! 🪄


Happy coding! ⚡️

MongodbMongooseNextjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.