Step 3

Let's connect the application to our MongoDB cluster (the one we have created for the YouNote API).

Open the data/db.js file and notice the URI is read from environment variable:

mongoose.connect(process.env.DB_URI, option);

Go to MongoDB Atlas website and get the connection URI for your cluster. For my MongoDB cloud cluster, the URI is:

mongodb+srv://younote-admin:<password>@younote-api.cwpws.mongodb.net/<dbname>?retryWrites=true&w=majority
  • Replace <password> with your database admin password. For me, this is the password for the user younote-admin.
  • Replace the <dbname> with the desired database name. I will continue to use younote-db as eventually I would like to bring the user registration/authentication into the YouNote App and its API.

Create a .env file in the users-app-starter folder with the following content:

DB_URI="YOUR-URI-GOES-HERE"

Open index.js file and import the db module:

const db = require("./data/db.js");

Connect to the database (place the following statement somewhere in index.js before using the app variable).

db.connect();

Save the index.js file and you should see your app is connected to the database:

[nodemon] restarting due to changes...
[nodemon] starting `node .`
Users' App is running at http://localhost:5001
Connected to MongoDB!

Notice the option variable in data/db.js which includes the following parameter:

useCreateIndex: true,

This parameter is included because we want the username attributes of each user to be unique, as it is indicated in mode/User.js:

const UserSchema = new Schema({
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
});