
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, we will set up Mongoose in our NextJS project. We'll create a connection file and add some basic error handling and connection options.
The project is located here:
To clone the project, run the following command:
//
git clone https://github.com/JSM-Masterclass-Experience/DatabaseStarter.git
Once you've cloned the project, navigate to the project directory and install the dependencies:
//
cd DatabaseStarter
npm install
This project is a basic NextJS project with a few pages and components. We'll be adding Mongoose to this project and implementing:
and more.
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
In our project's directory, install Mongoose:
//
npm install mongoose
The basic structure we recommend for a NextJS project with Mongoose is as follows:
You relevant folder structure should look like this:
We'll start by creating a :
// import mongoose
import mongoose from "mongoose";
db.ts;
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?
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.
import mongoose from "mongoose";
db.ts;
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:
import mongoose, { MongooseOptions } from "mongoose";
db.ts;
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'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 discuss our application and how we can structure our schema and models.