How to setup a MongoDB connection in a MERN environment

October 14, 2020

Assumptions

  • I am using a MERN stack
  • I have the following npm packages installed:
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "config": "^3.3.2",
    "express": "^4.17.1",
    "express-validator": "^6.6.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.10.9"
  },
  "devDependencies": {
    "@babel/cli": "^7.11.6",
    "@babel/core": "^7.11.6",
    "@babel/node": "^7.10.5",
    "@babel/preset-env": "^7.11.5",
    "concurrently": "^5.3.0",
    "nodemon": "^2.0.4"
  }
  • I also setup ES6 type module imports/exports instead of CommonJS require and module.export (e.g.: see details here).
  • have an Atlas MongoDB cluster setup

Setup config

I am using config to store and retrieve systemwide configuration.

Create config/default.json in your project root and populate with the Atlas MongoDB URI:

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

Create DB connection functionality

In the config folder create a new file db.js:

import mongoose from "mongoose"
import config from "config"

const db = config.get("mongoURI")

export default async () => {
  try {
    await mongoose.connect(db, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    })
  } catch (err) {
    console.error(err)
    process.exit(1)
  }
  console.log("DB connected")
}

Update server.js to actually connect to the database at startup

In your server.js import db.js and run the db connection function:

import express from "express"
import connectDB from "./config/db.js"

const app = express()

// connect to mongodb
connectDB()

const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`server started on port ${PORT}`))

If all went well your console output is something like this (I am using nodemon to manage my server):

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
server started on port 5000
DB connected

Hope this helps, cheers! emoji-thumbsup