Open In App

How to Deploy MongoDB App to Heroku?

Pre-requisite:- MongoDB

MongoDB is an open-source document-oriented database designed to store a large scale of data and allows you to work with that data very efficiently. It is categorized under the NoSQL (Not only SQL) database because the storage and retrieval of data in the MongoDB are not in the form of tables. 



Heroku

Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

In this article, we’re going to create a simple NodeJS ToDo application that we connect to MongoDB Cluster and Deploy into Heroku.



This article is divided into 3 steps to Deploy MongoDB App to Heroku.

Steps to Deploy MongoDB App on Heroku:

  1. Create MongoDB Atlas Cluster
  2. Create NodeJS ToDo App
  3. Installation of Heroku and Deployment

Step 1:- MongoDB Atlas Cluster

MongoDB Atlas Cluster is a NoSQL Database-as-a-Service offering in the public cloud (available in Microsoft Azure, Google Cloud Platform, and Amazon Web Services). 

Below are the steps to create a free MongoDB Cluster(a shared cluster)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

So now, we have set up our MongoDB Atlas Cluster, and we’re ready to move toward the To-Do NodeJS application.

Step 2: NodeJs

Node.js is an open-source and cross-platform runtime environment built on Chrome’s V8 JavaScript engine for executing JavaScript code outside of a browser. You need to recollect that NodeJS isn’t a framework, and it’s not a programming language. It provides an event-driven, non-blocking (asynchronous) I/O and cross-platform runtime environment for building highly scalable server-side applications using JavaScript.

For Downloading And Installation of NodeJS, use this link.

Now follow the steps below after installing.

  1. Create a folder called ToDO Project
  2. Open the PowerShell window on that ToDo Project folder.
  3. Run these commands on the PowerShell window.
# npm init -y
# npm install express mongoose ejs dotenv

4. Create a file with the name index.js and put this below code in the index.js file.




require("dotenv").config();
// basic syntax for dotenv module
// DotEnv is a lightweight npm package that
// automatically loads environment variables
// from a . env file into the process. env object
  
// Express is a minimal and flexible Node.js web 
// application framework that provides
//a robust set of features for web and mobile applications
  
const express = require("express");
  
// Mongoose is an Object Data Modeling (ODM) library 
// for MongoDB database and Node.js.
const mongoose = require("mongoose");
  
// creating nodejs app
const app = express();
  
// app to use body-parser
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
  
// app set to template engine called ejs
app.set("view engine", "ejs");
  
// url for mongodb cluster
const url = process.env.DB_URL;
  
// connecting to mongodb cluster
mongoose.connect(url);
  
// schema for storing the todo's in DB
const itemsSchema = {
  toDoItem: String,
};
  
// creating Collection in DB
const Item = mongoose.model("toDoItems", itemsSchema);
  
app.get("/", function (req, res) {
  // find all the inserted Items in DB
  Item.find({}, (err, toDoItems) => {
    if (!err) {
      res.render("index", {
        toDoItems: toDoItems,
      });
    }
  });
});
  
app.post("/", function (req, res) {
  //   store the toDo we're getting in variable toDo
  const toDo = req.body.toDo;
  
  const toDoItem = new Item({ toDoItem: toDo });
  
  //   store the toDo item in the DB
  toDoItem.save(() => {
    // redirect to home page
    res.redirect("/");
  });
});
  
app.listen(process.env.PORT || 3000);

       

5. Create a file with the name .env and put your Cluster URL we copied earlier as shown below.

 

        

6. Create a folder with name views in the project folder

7. Create a file with the name index.js in the views folder and put the below code in it




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>To Do List</title>
  </head>
  <body>
    <% toDoItems.map((item , number)=>{ %>
    <div style="border: 2 black">
      <p><%= number + 1 %> : <%= item.toDoItem %></p>
    </div>
    <% }) %>
  
    <form action="/" method="POST">
      <input
        type="text"
        name="toDo"
        placeholder="New Item"
        autocomplete="off"
        value=""
        autofocus
      />
      <button type="submit">+</button>
    </form>
  </body>
</html>

 

       In the PowerShell window, run the command

# node index.js

       Open your browser and search localhost:3000, and you should get the output as shown

 

 

 

 

Step 3: Use Heroku. It is a cloud-based application deployment and management service. For downloading and installation of Heroku, click here. So considering that you have installed Heroku CLI on your machine. Go to the official website of Heroku. Sign up if you haven’t yet, or Sign In.

 

 

       /node_modules
       npm-debug.log
       .DS_Store
       /*.env

    

 

git init
git add .
git commit -m "initial"

          This is basically the URL for our application generated by the Heroku

 

           web: node index.js

 

 

          ,"engines": {
          "node": "16.17.1"
           },

 

git add .
git commit -m "deployment setup is done"
git push heroku master

 

 

 

 

 

So we successfully deployed the MongoDB Application to Heroku.


Article Tags :