Connecting to MongoDB Atlas with Mongoose

In MongoDB Atlas on your Cluster page, click Connect > Connect your application > Copy the connection string

Create config folder. Inside, create default.json. With the config package, we can create global values that we can use throughout our application

In default.json:

{
   "mongoURI": "mongodb+srv://username:<password>@devconnector.cc6yr.mongodb.net/<dbname>?retryWrites=true&w=majority"
}

We use curly braces because this is json formatting

Replace <password> with your password. Replace <dbname> with your database’s name.

We could put our connection logic in the server file, but in order to not clutter it up, we can put it in a separate file within the config folder

We’ll call the file db.js (you can call it whatever you want) and this is what goes inside of it:

const mongoose = require('mongoose');
const config = require('config');
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
        await mongoose.connect(db, { useNewUrlParser: true });
        console.log("MongoDB connected...");
    } catch(err) {
        console.log(err.message);
        process.exit(1);
    }
}

module.exports = connectDB;

We add { useNewUrlParser: true } to our connect function in order to get rid of this error:

“(node:58034) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.”

Then, in our server file we can just import and call the connectDB() function:

const express = require("express");
const connectDB = require('./config/db');

const app = express();

connectDB();

app.get('/', (req, res) => res.send('API Running'));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log(`Server started on port ${PORT}`));