Step 12

We are going to have mongoose connect to our MongoDB cluster.

First, we install the dotenv package:

npm install dotenv

Then create a .env file in the root of your application with the following content:

DB_ADMIN_PASSWORD="your-password-goes-here"

Open the .gitignore file and add the following to it, to ensure the .env file is not stored in your git repository:

.env

Create a new file data/db.js with the following content:

require("dotenv").config();
const mongoose = require("mongoose");

const password = process.env.DB_ADMIN_PASSWORD;
const dbname = "younote-db";
const URI = `mongodb+srv://younote-admin:${password}@younote-api.cwpws.mongodb.net/${dbname}?retryWrites=true&w=majority`;
const option = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
};

function connect() {
  mongoose.connect(URI, option);

  mongoose.connection.on("error", (err) => {
    console.log(err);
  });

  mongoose.connection.on("open", () => {
    console.log("Connected to MongoDB!");
  });
}

module.exports = { connect };