- In this part we will connect our backend to our MongoDB Atlas instance.
- Since we have already installed our mongodb dependency we can start using it to setup our client
- Create a database.js file in our server folder, and add in the following code
require("dotenv").config();
const { MongoClient, ServerApiVersion } = require("mongodb");
const uri = process.env.MONGODB_URI || "mongodb://localhost:27017/";
const options = {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
}
};
let client;
const connectToMongoDB = async () => {
if (!client) {
try {
client = await MongoClient.connect(uri, options);
console.log("Connected to MongoDB");
} catch (error) {
console.log(error);
}
}
return client;
};
const getConnectedClient = () => client;
module.exports = { connectToMongoDB, getConnectedClient };
- First we need to setup some environment variables so we can keep our database connection string a secret
- Create a .env file in our server folder
- We need to get our MongoDB connection string head back to MongoDB Atlas and click on database
- Click on the Connect button and then select MongoDB for VS Code

- Copy the connection string that is provided and inside the .env file write in the following

- Replace
<password>
with your actual password that we made in the previous part, if you forgot it or did not write it down you will have to create a new password for your MongoDB Atlas instance under Database Access
- We will also create a PORT variable which we will use later
- Back in our database.js file let us walk through the code
- First, we will require and config our “dotenv” file so that we can use our variables from out .env file.
- We will then import
MongoClient
and ServerApiVersion
from “mongodb”
- We will setup our
uri
variable to be process.env.MONGODB_URI
which will get the MONGODB_URI
from .env file we previously setup.
- Then we will set an
options
objects with some default settings from the MongoDB documentation.
- Finally we will create a
client
variable that is initially set as undefined.