Building a Dynamic Web Application with Node.js, Express, and MongoDB

 Building a Dynamic Web Application with Node.js, Express, and MongoDB


In this tutorial, we will be building a dynamic web application using Node.js, Express, and MongoDB. Our web application will allow users to create, read, update, and delete data from a database using a user interface.


Step 1: Setting up the Project


First, let's create a new Node.js project and install the necessary dependencies:


bash


mkdir myapp

cd myapp

npm init

npm install express mongodb body-parser

We will also need to install MongoDB if it is not already installed on your system. You can download and install MongoDB from the official website: https://www.mongodb.com/download-center.


Step 2: Creating the Server


Next, let's create a server using Express. Create a new file called server.js and add the following code:


javascript


const express = require('express');

const bodyParser = require('body-parser');

const MongoClient = require('mongodb').MongoClient;


const app = express();

const port = 3000;


app.use(bodyParser.urlencoded({ extended: true }));


MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, (err, client) => {

  if (err) return console.log(err);

  db = client.db('myapp');


  app.listen(port, () => {

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

  });

});


app.get('/', (req, res) => {

  res.sendFile(__dirname + '/index.html');

});


app.post('/quotes', (req, res) => {

  db.collection('quotes').insertOne(req.body, (err, result) => {

    if (err) return console.log(err);


    console.log('Saved to database');

    res.redirect('/');

  });

});

This code sets up a server using Express, connects to a MongoDB database, and defines two routes: one for serving the index.html file, and one for handling form submissions.


Step 3: Creating the User Interface


Next, let's create the user interface for our web application. Create a new file called index.html and add the following code:


php


<!DOCTYPE html>

<html>

  <head>

    <title>My App</title>

  </head>

  <body>

    <h1>My App</h1>


    <form action="/quotes" method="post">

      <div>

        <label for="author">Author</label>

        <input type="text" id="author" name="author">

      </div>

      <div>

        <label for="quote">Quote</label>

        <textarea id="quote" name="quote"></textarea>

      </div>

      <button type="submit">Submit</button>

    </form>

  </body>

</html>

This code creates a simple form with fields for the author and quote, and a submit button. When the form is submitted, it sends a POST request to the /quotes route on our server.


Step 4: Displaying Data from the Database


Next, let's modify our server code to display data from the database. Add the following code to server.js:


javascript

Copy code

app.get('/quotes', (req, res) => {

  db.collection('quotes').find().toArray((err, results) => {

    if (err) return console.log(err);


    res.render('index.ejs', { quotes: results });

  });

});


app.set('view engine', 'ejs');

This code adds a new route for displaying data from the quotes collection in the database. We use the EJS templating engine to render the data in a template.


Create a new file called index.ejs and add the following code:


php


<!DOCTYPE

<html>

  <head>

    <title>My App</title>

  </head>

  <body>

    <h1>My App</h1>

css


<form action="/quotes" method="post">

  <div>

    <label for="author">Author</label>

    <input type="text" id="author" name="author">

  </div>

  <div>

    <label for="quote">Quote</label>

    <textarea id="quote" name="quote"></textarea>

  </div>

  <button type="submit">Submit</button>

</form>


<% if (quotes.length > 0) { %>

  <ul>

    <% for (var i=0; i<quotes.length; i++) { %>

      <li><%= quotes[i].author %> - <%= quotes[i].quote %></li>

    <% } %>

  </ul>

<% } %>

  </body>

</html>

```

This code adds a loop to display all of the quotes in the database.


Step 5: Updating and Deleting Data


Finally, let's add support for updating and deleting data from the database. Modify the server.js file to include the following code:


javascript


app.put('/quotes', (req, res) => {

  db.collection('quotes').findOneAndUpdate(

    { author: req.body.author },

    {

      $set: {

        quote: req.body.quote

      }

    },

    {

      upsert: true

    },

    (err, result) => {

      if (err) return res.send(500, err);

      res.send(result);

    }

  );

});


app.delete('/quotes', (req, res) => {

  db.collection('quotes').findOneAndDelete(

    { author: req.body.author },

    (err, result) => {

      if (err) return res.send(500, err);

      res.send(result);

    }

  );

});

This code adds new routes for updating and deleting data from the database. We use the findOneAndUpdate and findOneAndDelete methods provided by MongoDB to make the changes.


Conclusion


In this tutorial, we have built a dynamic web application using Node.js, Express, and MongoDB. Our application allows users to create, read, update, and delete data from a database using a user interface. This is just a starting point for building more complex web applications, but it provides a solid foundation to build upon.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...