Back to Blog

An Introductory Guide to Using React With MongoDB

Do you want an application that's not just easy to build but that can also efficiently handle large amounts of data? What could be better than a combination of the front-end library React and the MongoDB database. 

In this article, we'll not only get to know React and MongoDB, but we'll also set up the environment and integration of a React application with a MongoDB database. 

What Is React?

React is a free and open-source JavaScript library that solely helps in building a complex and interactive UI (user interface). 

One of the striking features of React is that you can break down the front end of your web application into multiple components. Subsequently, each component contains its own logic and design, which you can reuse anywhere with content updates but without page reloads. Since React follows a reusable component-based model, it's best suited for real-time, single-page mobile or web applications. 

React aims to resolve the problem of having a sluggish traditional DOM (Document Object Model). Instead of applying changes to the actual browser DOM, React creates an in-memory virtual DOM and efficiently updates only the necessary parts of the DOM to optimize UI rendering performance. 

What Is MongoDB?

MongoDB is an open-source NoSQL document-oriented database. Unlike a traditional relational database with fixed tables of rows and columns, MongoDB contains human-readable JSON-like documents with optional schemas. More about SQL vs. NoSQL here.

Having a flexible schema approach, MongoDB makes it easy to store structured and unstructured data and retrieve it in JSON format, suitable for API responses. Here’s a simple representation of data for MongoDB: 

{

"_id": 1,

"username": {

"first": "John",

"last": "Doe"

},

"contact": {

"email":"johndoe@gmail.com",

"phone":"+919999999999"

},

"address":"xyz"

}

Why Use React With MongoDB?

React and MongoDB are part of the popular MERN (MongoDB, Express, React, and Node.js) stack for web development. If you choose to use React with MongoDB, here are the benefits you can expect to get in return: 

  • Both are open-source technologies, which means you can directly contribute to improving the technology itself.
  • Reusable components with fast UI rendering.
  • No full-page refresh due to virtual DOM.
  • One-way data binding for efficient content updates to UI components.
  • Simple and human-readable JSON-format data to store and manage.
  • Cloud-compatible database than can handle large volumes of data.
  • Feature to store structured and unstructured information in the same document.
  • Data schema design is not required.

Setting Up the Development Environment for a React App

Before we get to building an application, there are some of prerequisites that we need to have on our system. This includes the Node.js runtime environment for executing JavaScript code server-side, npm (Node.js package manager, the default package manager for Node.js), the create-react-app utility to initiate a new React app, and a MongoDB database. Let's install and set up each of these components one by one. 

Installing Node.js and npm

We’ll start with installing Node.js, which by default includes the npm package manager. Once we have npm, we can install all required packages and modules for our React project. 

You can install Node.js in different ways, available for various platforms. One of the convenient ways to install Node.js is using the available prebuilt installer for macOS and Windows operating systems. 

If you’re using a Linux-based operating system, run the following script to install the latest version of Node.js: 

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

nvm install 20

Creating a React Application

Once you get npm on your system, you now need to install the create-react-app utility by running the following command in your terminal: 

npm install -g create-react-app

Let’s use create-react-app to quickly create a new React project with all the necessary configurations. Open the terminal, navigate to the directory where you want to create your project, and run the following command: 

create-react-app <project-name>

Here, replace <project-name> with your desired project name. The command will create a new folder with a default structure that includes a node_modules folder containing all npm packages and dependencies, a src folder where you’ll write React code, and a package.json file containing relevant project metadata, dependencies, scripts, and version information. 

React app directory structure
React app directory structure

Your development environment for the front end is now ready. Want to check that it's working? Run the following command in the terminal from your project folder:

npm start

React App running successfully
React App running successfully

Now, check out the http://localhost:3000 url in the browser where your development server is running. Whatever React code you write, you can now view its effect on that locally hosted UI server. 

React App running successfully

Setting Up MongoDB

Let’s also set up MongoDB locally by installing it on your machine. But before that, create a folder where you want to store all data on your local machine. 

mkdir <database-folder-name>

Next, download the archived package of the MongoDB Community Server package compatible with your operating system. Extract the downloaded TGZ file to wherever you want on your system and navigate to the bin file of the same folder where you’ll see the mongod executable. 

To start the MongoDB database server, open the terminal, navigate to the bin folder of the extracted file, and run the following command: 

sudo ./mongod - -dbpath <database-folder-path>

Here, replace <database-folder-path> with your respective database folder that you created earlier. 

MongoDB database running
MongoDB database running

If you’re uncomfortable interacting with a database in command line, you can also download and install the graphical application MongoDB Compass that's compatible with your respective operating system. 

MongoDB Compass
MongoDB Compass

Keep the MongoDB database server running in the command line and, using Compass, connect to the locally hosted database at the mongodb://localhost:27017 url. 

Setting up a database locally on your system might restrict your development on a single device. So, you can also opt for a free version of MongoDB Atlas, which is a cloud-based database service by MongoDB.

Connecting React to MongoDB

Since React is a UI development framework, you cannot directly connect it to MongoDB to perform CRUD operations. What you need is a back-end server that will act as an intermediary between React and MongoDB. 

Although, if you use the React-based Next.js web development framework, you can connect to MongoDB directly without a separate server. Still, you should not directly access the database from the client side due to security reasons. 

We can build a back-end server using the Express.js framework. It'll help to host RESTful APIs to receive requests from the front end, interact internally with the database, and send responses back to the front end. 

Setting Up Express Server

For creating a back-end server, let’s create a new directory. Navigate to the directory and initialize a new Node.js project using the following command: 

npm init -y

The command will create a package.json file in the project folder that keeps track of your project's dependencies and scripts. 

package.json
package.json

Now, let’s install the required packages Express and Mongoose using the npm package manager from inside the project directory. 

npm install express mongoose

Finally, create a new file named index.js which will act as an entry point for the server. Write the basic code to set up an Express server. 

const express = require('express');

const app = express();

app.use(express.json());

const port = process.env.PORT || 3001;

app.listen(port, () => {

console.log(`Server is running on port ${port}`);

});

Configuring a MongoDB Connection

Earlier, we set up the MongoDB server locally, so now let’s connect React with MongoDB using the Express server. 

For creating a connection between MongoDB and the Node.js runtime environment, we need a Mongoose library. You can add the following code in the index.js file for configuring the MongoDB connection: 

const mongoose = require('mongoose');

const MONGODB_URI = 'mongodb://localhost:27017/<database-name>';

mongoose.connect(MONGODB_URI, {

useNewUrlParser: true,

useUnifiedTopology: true

});

mongoose.connection.on('connected', () => {

console.log('MongoDB database connection established successfully');

});

mongoose.connection.on('error', (err) => {

console.error('MongoDB database connection error:', err);

});

Above, replace <database-name> with your own database name you want to give to it. Finally, start the server by running: 

node index.js

You should see the following result, which means the MongoDB database successfully connected to the Node.js server. 

Node server running
Node server running

You can now define your data model using Mongoose schemas and start interacting with your database from the Node.js application. You can also create APIs to get requests from React applications and send responses accordingly. 

Using MongoDB Directly From React

Have you ever wondered if you can connect to the MongoDB database directly from the React app without creating a Node.js server? Technically, React doesn’t allow directly connecting to a database. 

But luckily, Neurelo gives you the power to do so. How? By instantly turning your MongoDB database schema into auto-generated APIs. Instead of writing tons of code for building a back-end server, you just need a database schema. 

Once you have a schema, Neurelo reads it and auto-generates multiple routes like GET, PUT, POST, and DELETE to perform basic CRUD operations. If you want more details about the APIs, Neurelo also generates all the API docs based on your schema. Not just that, but you can also view insights from observability metrics for every API and query. 

Neurelo has a built-in Data Viewer which provides an intuitive single interface to visually explore, query, and manipulate data stored in the database. 

If you want to explore new ways of using databases on the client side without an intermediary, you can visit Neurelo's site, sign up, and try for free. 

Although, as earlier I mentioned, you should always be careful of the security risk that is exposed due to connecting MongoDB directly with React. If your project contains very sensitive data like financial details, you should prioritize using Express.js or any other server side framework as a pass through proxy. You can also make your own proxy server using PropelAuth or other options.

Conclusion

React is not just limited to web development. If you know the basics of React, you can extend that to mobile development as well as in the form of React Native. What could be more useful than combining React with the power of a MongoDB database? The duo can help you build a real-time application that works fast and handles diverse data types at a large scale. 

This post was written by Sarvottam Kumar. Sarvottam is a software engineer by profession with interest and experience in Blockchain, Angular, React, Java, and Flutter. He loves to explore the nuts and bolts of Linux and share his experience and insights of Linux and open source on the web/various prestigious portals.