How to Create a RESTful API Using Node, Express, and MongoDB

How to Create a RESTful API Using Node, Express, and MongoDB. In this post, we introduce Node.js, Express, MongoDB, RESTful API then show you how to use Node Express and MongoDB to develop REST APIs.

These days, the vast majority of applications you use have a client server architecture. The application itself is referred to as the client or the front end portion, and in order to load or retrieve the data, it must communicate with a server or the back end. In essence, REST is a standard for creating HTTP services, which are utilized to establish this connection. By utilizing Express JS as the back end server and MongoDB as the document store, the REST API technique is implementeable quickly.

Worldwide, developers use the open source database MongoDB, which is quite well known and in extensive use. One of the most well liked Node.js web frameworks, Express, offers view systems, middleware, and routing. Without spending a lot of time setting up a database, MongoDB enables developers to quickly create applications and websites. Before creating REST APIs with Node Express with MongoDB, let’s quickly go over this powerful Database platform.

What is MongoDB?

MongoDB is a non relational database management system that is open source and cross platform. MongoDB, which was created in 2009 by MongoDB Inc., groups data into documents and collections rather than tables using the document oriented Database Model. This enables it to store various kinds of data. It offers fast performance, multiple language support, and great features.

Popular NoSQL database MongoDB stores big data sets well and allows a flexible schema approach. It is written in a variety of programming languages, including Ruby, Perl, PHP, C++, Java, Python, and JavaScript. Additionally, it is distributed under the Server Side Public License (SSPL), which offers a special method for storing and retrieving large amounts of data.

Key Features of MongoDB

Here are a few of MongoDB’s salient characteristics that contribute to its rising recognition.

  • Uses horizontal scaling, unlike other SQL databases, enabling users to create clusters with real time replication. The ability to scale data across several Servers horizontally is made simple by MongoDB’s support for the sharding process.
  • MongoDB stores all of the gathered information in a document that resembles JSON and allows for additions and adjustments over time.

What are NodeJS and ExpressJS?

The V8 engine based open source runtime environment known as Node.js or Node enables programmers to create server side tools, programs, and applications in JavaScript. It is employed for JavaScript code execution outside of a browser. The Client Applications are powered by Back End Services, also known as APIs (Application Programming Interfaces), which are built using Node to be extremely scalable, data intensive, and real time.

Node is incredibly simple to use, and it may be used for agile development and prototyping. An extremely well liked back end web framework for Node.js is called Express.js or Express. Express is based on Node and provides a number of utilities that make dealing with Nodes considerably simpler and more enjoyable.

What is Restful API?

By offering easily accessible codes and information pipelines, an application programming interface (API) creates a connection between computers or between computer programs (applications). It is a kind of software interface that facilitates communication between different software programs by serving as a mediator. Distinct sorts of APIs (such as Program, Local, Web, or REST API) help developers create reliable digital solutions because there are many distinct application designs.

An adaptable, lightweight method of integrating computer applications is offered by REST APIs. You don’t need to worry about how to format your data because REST APIs are a straightforward and industry standard method of communication.

How to Create a RESTful API Using Node, Express, and MongoDB

In this section, we create a RESTful API using Node.js, Express and MongoDB.

Deploy MongoDB Atlas

Before getting started with Node Express MongoDB, you  need to deploy an Atlas Cluster. Navigate to the official website Getting Started with Atlas guide to creating a free Atlas Account. Go on to create your first cluster and get your connection string to the Database.

Now, you simply load the sample dataset by clicking on “Load Sample Data.” You now need to clone the project stub branch. Explore the full project in the following GitHub repo.

				
					git clone -b stub 
git@github.com:mongodb-developer/mongodb-express-rest-api-example.git
				
			

In the project, go to the “server” directory to install the needed packages.

				
					cd mongodb-express-rest-api-example/server
npm install
				
			

Connecting to MongoDB Atlas

The Express Server and MongoDB Atlas Cluster are now be connected. Create a config.env file in the Server Directory after finding your connection string. The connection string’s value is now assigned to a fresh ATLAS_URI variable. Don’t forget to substitute your database’s username and password for <username> and
<password>.

				
					ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
				
			

server/db/conn.js allows Atlas Database to be accessed globally by exporting a MongoDB Client that is used by any other module. Open server/db/conn.js and add the implementation of the connectToServer function as shown below.

				
					const {MongoClient} = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString,{
    useNewURLParser = true,
    useUnifiedTopology = true,
}) ;

let dbConnection;
module.exports={
    connectToServer: function(callback){
        client.connect(function(err, db){
            if(err || !db){
                return callback(err);
            }
            dbConnection = db.db("sample_airbnb");
            console.log("Connection Done ");
            return callback();
        })
    },
    getDb:function(){
        return dbConnection;
    },
}

				
			

This module exports the _db variable, which holds the “sample_airbnb” Database level object.

Add REST API CRUD Routes

Express.js explore the REST API routes to your application to perform Create, Read, Update, and Delete (CRUD) operations. The file that hosts the routes is “server/routes/record.js”. It uses the Express Router feature.

Read Routes

Whenever the /listings path on a GET method is called, the Read route is used. It uses a collection.find() method to query the listingAndReviews collection for the first 50 available listings.

				
					// This section will help you get a list of all the documents.
recordRoutes.route("/listings").get(async function (req, res) {
  const dbConnect = dbo.getDb();

  dbConnect
    .collection("listingsAndReviews")
    .find({}).limit(50)
    .toArray(function (err, result) {
      if (err) {
        res.status(400).send("Error fetching listings!");
     } else {
        res.json(result);
      }
    });
});
				
			

Create Routes

The Create route documents a “match” swipe in a “matches” collection. The body of this POST method has a user session_id, the swiped direction, and the listing_id in order to create a “match” document.

				
					// This section will help you create a new document.
recordRoutes.route("/listings/recordSwipe").post(function (req, res) {
  const dbConnect = dbo.getDb();
  const matchDocument = {
    listing_id: req.body.id,
    last_modified: new Date(),
    session_id: req.body.session_id,
    direction: req.body.direction
  };

  dbConnect
    .collection("matches")
    .insertOne(matchDocument, function (err, result) {
      if (err) {
        res.status(400).send("Error inserting matches!");
      } else {
        console.log(`Added a new match with id ${result.insertedId}`);
        res.status(204).send();
      }
    });
});

				
			

Update Routes

The Update route updates the “likes” tab on a listing object. This is also done via a POST method.

				
					// This section will help you update a document by id.
recordRoutes.route("/listings/updateLike").post(function (req, res) {
  const dbConnect = dbo.getDb();
  const listingQuery = { _id: req.body.id };
  const updates = {
    $inc: {
      likes: 1
    }
  };

  dbConnect
    .collection("listingsAndReviews")
    .updateOne(listingQuery, updates, function (err, _result) {
      if (err) {
        res.status(400).send(`Error updating likes on listing with id ${listingQuery.id}!`);
      } else {
        console.log("1 document updated");
      }
    });
});

				
			

Delete Routes

A listing is deleted from the Database after a listing is dropped. This is done via the Delete route.

				
					// This section will help you delete a record.
recordRoutes.route("/listings/delete/:id").delete((req, res) => {
  const dbConnect = dbo.getDb();
  const listingQuery = { listing_id: req.body.id };

  dbConnect
    .collection("listingsAndReviews")
    .deleteOne(listingQuery, function (err, _result) {
      if (err) {
        res.status(400).send(`Error deleting listing with id ${listingQuery.listing_id}!`);
      } else {
        console.log("1 document deleted");
      }
    });
});

				
			

Now go ahead and launch the Server using the npm command as shown below

				
					npm start
				
			

Setting up the Front-End

As we all know, the React application mainly consists of the App.js React file and class.

				
					import './App.css';
import TinderCard from 'react-tinder-card'
import axios from 'axios';
import { Component } from 'react';
import { v4 as uuid } from 'uuid';

class App extends Component {
  constructor() {
    super();

    this.state = {
      data: [],
      session_id: uuid(),
      liked: false
    };
    this.handleClick = this.handleClick.bind(this);
    this.showDetails = this.showDetails.bind(this);
  }

  async onSwipe(direction, listingId, sessionId) {
    this.setState({
      liked: false
    });


    if (direction === "left") {
      await axios.delete(`http://localhost:5000/listings/delete/${listingId}`)
    } else {
      await axios.post("http://localhost:5000/listings/recordSwipe", { id: listingId, session_id: sessionId, direction })
    }
  }

  async handleClick(listingId) {
    this.setState({
      liked: !this.state.liked
    });

    await axios.post("http://localhost:5000/listings/updateLike", { id: listingId });
  }

  showDetails(listing) {
    alert(`Name: ${listing.name}n Price : $${listing.price['$numberDecimal']} n Minimum Nights : ${listing.minimum_nights}n Beds : ${listing.beds}`);
  }

  async componentWillMount() {
    const response = await axios.get(`http://localhost:5000/listings`);
    const json = await response.data;
    this.setState({ data: json });
  }

  render() {
    const likeButtonLabel = this.state.liked ? '❤' : 'Like';

    return (
        <div className="app">
          <div>
            <h1>LisTinder</h1>
            <h2>Swipe left for drop or right to save...</h2>

            <div className="card-container">
            {this.state.data.map((listing) =>
              <TinderCard className='swipe' key={listing.name} onSwipe={(dir) => this.onSwipe(dir, listing._id)}  >
                <div style={{ backgroundImage: 'url(' + listing.images.picture_url + ')' }} className='card'>
                  <div className="card-details">
                    <h3>{listing.name}</h3>
                    <div className="card-actions">
                      <button className="button" onClick={() => this.handleClick(listing._id)}>{likeButtonLabel}</button>
                      <button className="button" onClick={() => this.showDetails(listing)}>See Details</button>
                    </div>
                  </div>
                </div>
              </TinderCard>
            )}
            </div>
          </div>
        </div>
    );
  }
}

export default App;
				
			

To enhance the front end of your app, utilize third party modules to create swiping tiles and graphics. After installing any necessary modules, open a new terminal and start the application you just built with Node Express MongoDB.

				
					cd ../app/listings
npm install
npm start
				
			

All the components of your app are running, you may also test it by opening http://localhost:3000. Your REST application built with Node Express MongoDB is now complete.

Thank you for reading How to Create a RESTful API Using Node, Express, and MongoDB. We shall conclude.

How to Create a RESTful API Using Node, Express, and MongoDB Conclusion

In today’s digital age, APIs have become ubiquitous, finding their way into virtually every website. To create a robust MongoDB stack design, many developers turn to Express to create a Back End Middleware that runs on Node.js Server, allowing for the development of a REST API. This article provides step by step guidance on how to create a REST API using Node Express MongoDB, enabling you to perform CRUD operations with ease.

Avatar for Hitesh Jethva
Hitesh Jethva

I am a fan of open source technology and have more than 10 years of experience working with Linux and Open Source technologies. I am one of the Linux technical writers for Cloud Infrastructure Services.

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x