4. Connect to Your MongoDB Database


In this tutorial you will modify files in your project to configure and create a connection between your API server and the MongoDB database hosted on Atlas.  This connection will allow the API server (via mongoose) to create, modify, and delete documents in the database.

Edit Your .env File

Open your .env file in VSC.  Add a line that starts with MONGODB_URL= followed by your database connection string.  Remember to replace <db_password> in the connection string with the password to your database.  

Your .env file should look similar to the text below.

PORT=3001
MONGODB_URL=mongodb+srv://admin:thisismypassword@cluster0.8db675rs.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0

 

Create a Script to Create a Mongoose Connection

Create a file named mongoose.js in the db directory and copy the following code to the file.

import { connect } from 'mongoose'

console.log(`Connecting to Atlas`)

connect(process.env.MONGODB_URL)
    .then(() => { console.log('Connection to database successful.') })
    .catch((e) => { console.log('Error: ' + e) })

 

Run the Connection Script in app.js

Add the following line as the first line in src/app.js.

import './db/mongoose.js'

 

Test the Connection

Run npm run dev from the command line. You should see the following output on the command line (the order may be different).
Connecting to Atlas
Listening on port 3001
Connection to database successful.
If an error was printed, revisit the instructions above as something is incorrect.

 

Push Code to GitHub

You know the drill.  Commit your changes to your repository and push the changes to GitHub.