Photo by Henry Dick on Unsplash

Connect Your Node.js backend to a MongoDB Database

Robert K.
5 min readOct 26, 2020

--

Full-stack development is a balance between a strong back end and an interactive and responsive front end. After learning JavaScript during my time at Flatiron School I fell in love with its flexibility and started to look into Node.js

Node.js is an asynchronous JavaScript Runtime built on Chrome’s V8 engine. It can handle many connections concurrently and sleeps when there’s no work to be done. It’s non-blocking, so you don’t have to worry about multiple requests slowing down the experience for some users. This means scalable systems are very reasonable to develop using Node.js.

Gaining popularity over the past several years is the MERN stack. It takes a fast SPA front end and connects it to a MongoDB NoSQL database through a node.js backend.

In this article, we are going to spin up a new MongoDB Atlas Cloud database and connect it to a node.js backend.

Let’s get the set up done.

MongoDB

Firstly you’ll need an account on mongoDB.com. After making an account you will want to start up a new project.

mongoDB project Set up — naming your project

Name your project and continue with Next

If you are working in a team add them and assign them permissions using the next prompt. If you are working by yourself just continue through this step

adding team members to mongoDB

To get our DB up and running we are going to need to make a new cluster. Here is where you can choose different pricing options based on your needs. For the personal project I’m working on we’re going to stick with the shared clusters and the free tier.

Creating our first cluster
choosing our cluster type

You’ll be given the option to choose your cloud provider and region. I went with google cloud and chose a region closest to me. Make sure to confirm you are in the M0 Sandbox and that the price to use this DB is free. When you’ve chosen your options choose Create Cluster

finishing details for Atlas set up

It will take a couple of minutes to spin up the cluster before you are able to use it.

While that is happening let’s build the basics of our Node.js backend so we can start testing once it's up and running.

In a project directory of your choosing ( I used a create-react-app shell since I’ll be adding a front end later) create a backend folder. In that folder create a server.js file. Here we will write the basics of our backend server. Before that, we will need to install several packages.

First, make sure you have node installed on your machine by running node -v in the terminal. If you get a version number you’re good; if not, install node before proceeding. cd into your backend directory for the next steps.

We need to create a package.json file first by running npm init -y

Now install a few dependencies.

npm install express cors mongoose dotenv

If you are interested in learning about these packages in more detail and the role they play you can do so here.

express cors mongoose dotenv

We will install one package globally to make sure we are able to use it anywhere on our machine.

npm install -g nodemon

nodemon docs

Our basic server is going to create an Express server, add our cors and express middlewares (since we are sending and receiving JSON), and listen for requests on port 5000. Here is the code.

Now we can run our server via the terminal using the nodemon server command. Nodemon is going to listen for changes in our node application and restart the server as needed so we don’t have to worry about resetting it every time. (if you need to hard reset you can use the rs command or ctrl-c to terminate it)

You should be able to see your server running in your terminal.

our node.js server listening for requests.

Almost there!

We’re going to connect our MongoDB Atlas database to our node.js backend.

To do this we’re going to require mongoose, a package that makes working with MongoDB via node.js easier. Add the following line after requiring cors.

const mongoose = require('mongoose')

After the lines connecting our middleware ( app.use(express.json());), we are going to add the following.

Now to get the uri from MongoDB. First, create a .env file in the backend directory. Here’s how to get the uri from the MongoDB dashboard.

Here we need to add our current IP address to the whitelist so it lets us through security. We also need a database username and password.

Once you have those click on Choose a connection method

You should replace the <password> with the password you just created for your database user. It will end up looking like this.

ATLAS_URI=mongodb+srv://rkadmin:<YOUR PASSWORD HERE>@cluster0.o2biz.mongodb.net/<dbname>?retryWrites=true&w=majority

Check your server for your new console.log message. ( you might have to restart it )

our nodejs backend is connected to our MongoDB Atlas

Congratulations. You took the first step to getting a node.js backend up and running and you connected it to a MongoDB Atlas.

Next week I’ll be building on this, adding a few models to the db and testing it with Insomnia.

Stay Tuned

Happy Hacking

Resources:

Connect with me:

--

--

Robert K.

Full- Stack Software Engineer with a former life in high-end restaurant management. Currently working in React JS and Ruby on Rails.