Course

Setting Up Mongoose in NextJS

In this lesson, we will set up Mongoose in a NextJS project.

Step 1: Scaffold a NextJS Project

If you don't already have a NextJS project, you can create one using the following command:

//
npx create-next-app@latest my-nextjs-project

Follow the guided instruction from the command-line tool. We'll use typescript and the app router for all of the examples in this course.

Step 2: Create a database

Before we can connect to a database, we need to create one. You can create a free MongoDB database using MongoDB Atlas. If you've never created a MongoDB database before, you can follow register for an account here.

Once you've followed the video, we'll add the connection string to our .env.local file.

//
MONGODB_URI=your_connection_string

Step 3: Install Mongoose

Navigate to the project directory and install Mongoose:

//
cd my-nextjs-project
npm install mongoose

Step 4: Create our folder structure and connection file

The basic structure we recommend for a NextJS project with Mongoose is as follows:

  1. Create a folder called lib in the root of your project.
  2. Inside the lib folder, create a file called db.ts (this is our connection file).
  3. Inside the lib folder, create a folder called models (this is where we'll store our Mongoose models).

You relevant folder structure should look like this:

app
lib
models
db.ts

We'll start by creating a :

db.ts
// import mongoose
import mongoose from 'mongoose';

async function dbConnect(): Promise<Connection> {
  // get the connection string from the environment
  const mongoURI = process.env.MONGODB_URI;
  await mongoose.connect(mongoURI);

  // return the connection object
  return mongoose.connection;
}

export default dbConnect;

This is a really basic connection file. We're simply creating a function that connects to the database using the connection string we stored in our file.

Do you see any potential issues with this code?

monkey

This code will connect to the database every time it's called. This is not ideal for a production application.

There's also no error handling in this code. If the connection fails, the application will crash.

To make this truly robust- we should add error handling and connection options. First let's address how to make this function only connect once.

db.ts
import mongoose from 'mongoose';

async function dbConnect() {
  // check if we have a connection to the database or if it's currently connecting
  if (mongoose.connection.readyState === 0) {
    const mongoURI = process.env.MONGODB_URI;

    await mongoose.connect(mongoURI);
  }

  // return the connection object
  return mongoose.connection;
}

This code checks if we have a connection to the database before trying to connect. If we're not connected, it will connect. If we are connected, it will return the connection we already have

Next, let's add some error handling and connection options and see our finished connection file:

db.ts
import mongoose, { MongooseOptions } from 'mongoose';

async function dbConnect(){
  if (mongoose.connection.readyState === 0) {
    const mongoURI = process.env.MONGODB_URI;

    if (!mongoURI) {
      throw new Error('Please define the MONGODB_URI environment variable.');
    }

    const mongooseOpts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    } as MongooseOptions;

    await mongoose.connect(mongoURI, mongooseOpts);
  }

  return mongoose.connection;
}

This code will throw an error if the environment variable is not defined. It also adds some connection options to the connection.

The connection options are important. They tell Mongoose how to connect to the database. In this case, we're telling Mongoose to use the new URL parser and the new server discovery and monitoring engine. These options are required for Mongoose to work with the latest version of MongoDB.

You're now ready to begin creating models and interacting with your database. To connect in a server action or API route, you can use the following code:

//
"use server"
import dbConnect from 'lib/db';

export async function exampleServerAction() {
  await dbConnect();
  // do something with the database or models
}

Conclusion

You've now set up Mongoose in a NextJS project. You've created a connection file and added some basic error handling and connection options. You're now ready to create models and interact with your database.

In the next lesson, we'll create a basic model and interact with our database.

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Creating a Models and Actions