'How can I connect to Mongodb Atlas

I am trying to connect to MongoDB atlas from node.js but I keep getting an error. I have whitelisted my ip address in database access and also allowed all ips but the issue keeps on persisting. Also for the record, I have counterchecked and my password as well as username are all correct. Could someone help me out? here is my database connection code

const mongoose = require("mongoose");
const connectDB = (url) => {
  console.info(`Trying to connect to ${url}...`);
  try {
    mongoose.connect(url, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
     
    });
  } catch (error) {
    console.log(error);
  }
};
module.exports = connectDB;

and here is my uri

DATABASE_URI =mongodb+srv://pepela:[email protected]/myFirstDatabase?retryWrites=true&w=majority


Solution 1:[1]

I'm beginner, but I can show u how I connected my atlas, I will use your data.

First I've created file named "config.js" :

module.exports = {
  databaseUri: "mongodb+srv://pepela:[email protected]/myFirstDatabase?retryWrites=true&w=majority",
}

Then in file where i connecting my MongoDB i called it server.js i have something like this

const mongoose = require("mongoose");

//im getting my MongoDB connection link from config.js file
const {databaseUri} = require("./config");

// and then the connection function 
mongoose.connect(databaseUri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
})
  .then(() => {
    console.log('MongoDB Connected')
  })
  .catch(err => console.log(err));

Purpose of having these databaseUri in separate file is for protection, when I'm pushing my code to GitHub I add it to .gitignore file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bartheus