The Talent500 Blog
MongoDB

A Comprehensive Guide to Building a Web Application with MongoDB

As the popularity of web applications grows, developers continue to explore new and efficient ways to build them. One such method is using MongoDB, a NoSQL database that allows for flexible and scalable data storage. 

In this comprehensive guide, we will walk through the process of building a web application with MongoDB, step by step. We will cover everything from setting up a development environment to deploying the application to a web server.

Before we begin, make sure that you have the following software installed on your computer:

  • Node.js and npm
  • MongoDB

A text editor (e.g. Visual Studio Code)

Step 1: Set Up a new Node.js Project

A Comprehensive Guide to Building a Web Application with MongoDB 1

First, we need to create a new Node.js project by running the following command in your terminal or command prompt:

npm init

This will create a package.json file that will keep track of your project’s dependencies. Follow the prompts to set up your project.

Step 2: Install the Necessary Dependencies

A Comprehensive Guide to Building a Web Application with MongoDB 2

Next, we need to install the necessary packages for our project. We will use Express.js as our web framework and Mongoose as our MongoDB ODM (Object Document Mapper). Run the following command to install these packages:

npm install express mongoose

Step 3: Set up the Express.js Server

A Comprehensive Guide to Building a Web Application with MongoDB 3

Now that we have installed the necessary packages, let’s set up our server. Create a new file called server.js in the root directory of your project and add the following code:

const express = require(‘express’);

const mongoose = require(‘mongoose’);

 

// Create a new Express.js instance

const app = express();

 

// Set up middleware

app.use(express.json());

 

// Connect to the MongoDB database

mongoose.connect(‘mongodb://localhost/myapp’, {

  useNewUrlParser: true,

  useUnifiedTopology: true,

});

 

// Define a schema for our data

const itemSchema = new mongoose.Schema({

  name: String,

  description: String,

});

 

// Define a model based on the schema

const Item = mongoose.model(‘Item’, itemSchema);

 

// Define routes

app.get(‘/items’, async (req, res) => {

  const items = await Item.find();

  res.json(items);

});

 

app.post(‘/items’, async (req, res) => {

  const item = new Item(req.body);

  await item.save();

  res.json(item);

});

 

// Start the server

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

  console.log(`Server listening on port ${PORT}`);

});

 

Let’s go through this code step by step:

➡️We require the Express.js and Mongoose packages at the beginning of our file.

➡️We create a new instance of Express.js and set it to the app variable.

➡️We set up middleware to parse JSON data sent to our server.

➡️We connect to our MongoDB database using the mongoose.connect method. 

➡️Replace myapp with the name of your database.

➡️We define a schema for our data using the mongoose.Schema method. In this case, our schema has two properties: name and description.

➡️We define a model based on our schema using the mongoose.model method. This will allow us to interact with our data using JavaScript objects instead of raw MongoDB queries.

➡️We define two routes: a GET route for retrieving all items in the database, and a POST route for adding a new item to the database.

➡️We start the server by calling the app.listen method. This will start a new web server that listens for requests on port 3000 by default.

Step 4: Test the Server

A Comprehensive Guide to Building a Web Application with MongoDB 4

Now that we have set up our server, let’s test it. Run the following command to start the server:

 

node server.js

This will start the server and print a message to the console indicating that it is listening on port 3000.

  • Next, open your web browser and navigate to http://localhost:3000/items. You should see an empty array [] because we haven’t added any items to the database yet.
  • Let’s add some data to the database by sending a POST request http://localhost:3000/items

You can use a tool like Postman or cURL to send the request, or you can use the following command in your terminal:

curl -X POST -H “Content-Type: application/json” -d ‘{“name”: “Item 1”, “description”: “This is item 1”}’ 

http://localhost:3000/items

This will add a new item to the database with the name “Item 1” and description “This is item 1”. If you refresh your web browser and navigate to http://localhost:3000/items, you should see an array with one item in it.

Step 5: Build the Front-End

A Comprehensive Guide to Building a Web Application with MongoDB 5

Now that we have our back-end server set up, let’s build the front-end using HTML, CSS, and JavaScript. Create a new file called index.html in the root directory of your project and add the following code:

 

<!DOCTYPE html>

<html>

<head>

  <title>My App</title>

  <style>

    /* Add some basic styles */

    body {

      font-family: sans-serif;

    }

    input, button {

      font-size: 1rem;

      padding: 0.5rem;

    }

    button {

      margin-left: 0.5rem;

    }

    ul {

      list-style: none;

      padding: 0;

    }

    li {

      margin-bottom: 0.5rem;

    }

    .item {

      background-color: #eee;

      padding: 1rem;

      border-radius: 0.25rem;

    }

  </style>

</head>

<body>

  <h1>My App</h1>

  <form>

    <label>

      Name:

      <input type=”text” name=”name”>

    </label>

    <label>

      Description:

      <input type=”text” name=”description”>

    </label>

    <button type=”submit”>Add Item</button>

  </form>

  <ul id=”item-list”></ul>

  <script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>

  <script>

    // Define a function to render the items list

    function renderItemList(items) {

      $(‘#item-list’).empty();

      for (const item of items) {

        const $li = $(‘<li>’).addClass(‘item’);

        $(‘<h2>’).text(item.name).appendTo($li);

        $(‘<p>’).text(item.description).appendTo($li);

        $li.appendTo($(‘#item-list’));

      }

    }

 

    // Define a function to add a new item

    async function addItem(item) {

      await $.ajax({

        method: ‘POST’,

        url: ‘/items’,

        contentType: ‘application/json’,

        data: JSON.stringify(item),

      });

    }

 

    // Bind event listeners

    $(‘form’).on(‘submit’, async function(event) {

      event.preventDefault();

      const $nameInput = $(‘input[name=”name”]’);

      const $descriptionInput = $(‘input[name=”description”]’);

      const item = {

        name: $nameInput.val(),

        description: $descriptionInput.val(),

      };

      await addItem(item);

      $nameInput.val(”);

      $descriptionInput.val(”);

     

});

 

  const items = await $.getJSON(‘/items’);

  renderItemList(items);

});

 

// Load initial items

$(async function() {

  const items = await $.getJSON(‘/items’);

  renderItemList(items);

});

  </script>

</body>

</html>

“`

This code defines a basic HTML form for adding items, an unordered list for displaying the items, and some basic styles. It also includes the jQuery library and some JavaScript code for sending requests to the server and rendering the items list.

Step 6: Test the app

A Comprehensive Guide to Building a Web Application with MongoDB 6

Now that we have both the back-end and front-end code written, let’s test the app to make sure everything is working correctly. Start the server by running the following command in your terminal:

node server.js

Then, open your web browser and navigate to http://localhost:3000. You should see a form for adding items and an empty list. Try adding a few items to the list using the form. Each time you add an item, it should appear at the top of the list.

Conclusion

Kudos to you, you’ve successfully built a web application with MongoDB! Of course, this is just the beginning. There are many other features you could add to the app, such as editing and deleting items, filtering and sorting the items list, and adding authentication and authorization. But hopefully, this guide has given you a solid foundation for building your own MongoDB-powered web apps. Good luck, and happy coding!

0
Afreen Khalfe

Afreen Khalfe

A professional writer and graphic design expert. She loves writing about technology trends, web development, coding, and much more. A strong lady who loves to sit around nature and hear nature’s sound.

Add comment