Integrating MongoDB with Node.js

A robust modern-day application has a medium of storing data at its backend such as Node application which is able to work with both non-relational (such as PostgresQL, MongoDB) and relational (such as MySQL, Oracle).

MongoDB is a non-relational database that is relatively easy to use and powerful, and if you are a Node.js developer who wants to learn the benefits that it brings and how to get started with creating a secure integration with your Node application, this is the guide for you!

In this article, we will learn how to integrate/connect to MongoDB; a very popular non-relational database with Node.js and see how we can use it within Node applications.

Note: To follow along, you will need to install Node.js. You can download the longest stable version (LTS) and install on your local machine from its Official Download Page.

Brief Info on MongoDB

MongoDB is the most popular and most advanced document-based database, where all data is stored in Binary JSON (JavaScript Object Notation) known as BSON. A BSON is a document, with no need for a predefined data schema. It allows data that is frequently accessed together by an application to be stored in the same place and makes database reading easy and fast.

Unlike relational tables, collections are self-contained, this makes them much easier to work with. When a new document is created on a MongoDB collection, an ID gets assigned to it to make it unique to that collection, and inside the document, multiple fields can be defined; where the value could be a variant of data types ranging from arrays, strings, integers, objects and so on.

In order to manipulate data, the query API is useful for performing the basic Create, Read, Update and Delete (CRUD) operations across the database. Secondary indexes can also be created to ensure optimization and make common queries extremely fast. Geospatial queries are also supported, which make it possible to find documents in a specific geographical location.

Getting Started with MongoDB

Before we get started with connecting to MongoDB from a Node application, head to the official MongoDB website to sign up with the Try Free button (if you do not already have an account):

After creating your account, head over to click the Build a Database button, and click to create a database:

Next, create a Shared Cluster (it is free forever!) and give it a name of your choice.

The Shared Cluster is ideal for experimenting in a limited sandbox. You can upgrade to a production cluster anytime.

When you have successfully created a Cluster, click the Connect button to connect to the Cluster:

You are now shown four different ways on how to connect with MongoDB, but since we wish to connected to a Node application, let us choose the Connect your application option:

You would then be prompted to choose a connection method. Here, make sure to select Node.js as your driver, and choose an appropriate version (I am using 4.1 or later while writing this article).

We are also shown a connection string which is useful for connecting our MongoDB cluster to a Node application:

Now, we need to create a Node.js application to connect to the MongoDB database.

Building the Node Application

In your preferred directory for this project, create a new folder:

$ mkdir integrating-mongodb-node

Then, run npm init in the terminal, in order to initialize a Node application with a package.json file that makes it possible for us to track application dependencies:

$ npm init

package name: (codes) integrating-mongodb-node
version: (1.0.0)
description: learning how to connect mongodb to a node app
entry point: (server.js)
test command:
git repository:
keywords:
author:
Is this OK? (yes) yes
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Now that we have successfully initialized package.json, let us go ahead to install two packages that will be helpful in building our server. The first is Express.js, which is a web framework for fast and easy development of Node applications:

$ yarn add express -D

The second packages we would install is the Mongoose package, which would help us to build appropriate schema for our database in the Node app:

$ yarn add mongoose -D

With the required development dependencies now installed successfully, we can now write code to connect our MongoDB database to our Node application.

In the directory that we just created for the project, create a server.js file

$ touch server.js

Next, we define the basic setup for the Node application in server.js, by creating a simple express server.

// server.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();

const port = 8000;

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

We can confirm that our server is running as it ought to, by running the following code in the terminal.

$ node server.js

Which should result in:

Server started at port 8000

Now, you can head back to your MongoDB dashboard to copy the URI (Uniform Resource Identifier) in order to connect the Node app to the database.

I server.js create a variable to store the uniform resource identifier, and on the URI replace <password> with the password of your MongoDB account.

// server.js

const express = require("express");
const mongoose = require("mongoose");
const app = express();

const uri =
  "mongodb+srv://UcheAzubuko:<password>@stackabusecluster.fgavg5s.mongodb.net/?retryWrites=true&w=majority";

const port = 8000;

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

Next, we create an asynchronous function to enable us to connect to MongoDB, because we do not know how long it may take for the function to complete before we get connected to the database:

const express = require("express");
const mongoose = require("mongoose");
const app = express();

const uri =
  "mongodb+srv://UcheAzubuko:<password>@stackabusecluster.fgavg5s.mongodb.net/?retryWrites=true&w=majority";
async function connect() {
  try {
    await mongoose.connect(uri);
    console.log("Connected to MongoDB");
  } catch (error) {
    console.log(error);
  }
}
connect();

const port = 8000;
app.listen(port, () => {
  console.log(`Server started at port ${port}`);
});

We have created an asynchronous function which logs a Connected to MongoDB message when a connection has been successfully established between MongoDB and the Node app, and logs any errors if an error occurs.

Now, we should restart the server:

$ node server.js

And get a successfully message that informs us that a secure connection has now been establish between the MongoDB database and Node application:

Server started at port 8000
Connected to MongoDB

At this point, when you head back to your dashboard for your project cluster, you will now see information that shows that there has been a connection to the database recently:

Alright folks, that is it! We have successfully integrated a MongoDB database within a Node.js application.

Conclusion

In this article, we have learned how to create a secure connection between a Node.js application and a MongoDB database. Now, you can easily do the same when you need to build an application using MongoDB; a very popular non-relational database in the ecosystem.

Do not forget that the MongoDB Documentation is your best friend for learning about MongoDB, and to learn more about building Express applications, reach out to the Express Documentation too.

If you get stuck while following the tutorial, feel free to thinker through the GitHub repo for the project to find your way.

Additional Resources

Last Updated: April 20th, 2023
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Uchechukwu AzubukoAuthor

Uchechukwu Azubuko is a Software Engineer and STEM Educator passionate about making things that propel sustainable impact and an advocate for women in tech.

He enjoys having specific pursuits and teaching people better ways to live and work - to give them the confidence to succeed and the curiosity required to make the most of life.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms