title: Connect to MongoDB cluster
body: <p>Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by &quot;connect with the MongoDB shell&quot;, but this time I want to connect with the &quot;connect your application&quot; option.</p>
  <p>When I hit <code>mongosh</code> in the embedded terminal in my mac, below was returned.</p>
  <pre><code>Connecting to:      mongodb://127.0.0.1:27017/?directConnection=true&amp;serverSelectionTimeoutMS=2000&amp;appName=mongosh+1.2.2
  Using MongoDB:      5.0.6
  Using Mongosh:      1.2.2
  
  ...
  ...
  ...
  
  test&gt; 
  </code></pre>
  <p>Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.</p>
  <p>Thanks for your time for dedication here. So appreciate it.</p>
  <pre class="lang-js prettyprint-override"><code>// this is db.js file in a config folder. 
  const mongoose = require('mongoose')
  
  // It must be a promise function to connect db
  const connectDB = async () =&gt; {
    try {
      console.log(`try`)
      const conn = await mongoose.connect(process.env.MONGO_URI, {
        useNewUrlParser: true, 
        useUnifiedTopology: true, 
        dbName: 'expense2'
      });
  
      console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
    } catch (error) {
      console.log(`Error: ${error.message}`.red)
      process.exit(1);
    }
  }
  
  module.exports = connectDB;
  
  /* 
  Here is the error happened
  Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
  [nodemon] app crashed - waiting for file changes before starting...
  */
  </code></pre>
  <p>config.env in the config folder as well.</p>
  <pre><code>NODE_ENV = development;
  PORT=5000
  MONGO_URI=mongodb+srv://mongo:mongo@cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&amp;w=majority
  </code></pre>
  <pre class="lang-js prettyprint-override"><code>// server.js file
  const express = require('express');
  const dotenv = require('dotenv');
  const colors = require('colors');
  const morgan = require('colors');
  const connectDB = require('./config/db')
  
  dotenv.config({ path: &quot;./config/config.env&quot; })
  
  connectDB();
  const app = express();
  
  const transactionsRouter = require('./routes/transactions')
  app.use('/transactions', transactionsRouter)
  
  
  const PORT = process.env.PORT || 5000;
  
  app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));
  </code></pre>