,

🌟 Building and Displaying Forms using EJS, Express, and Mongoose | Abhishek’s Coding Tutorial 🚀

Posted by


In this tutorial, we will be creating forms using EJS, Express, and Mongoose in a Node.js environment. Forms are an essential part of any web application as they allow users to input data that can be processed by the server. We will be using EJS as our templating engine, Express as our web framework, and Mongoose as our object modeling tool for MongoDB.

Before we dive into the tutorial, make sure you have Node.js and MongoDB installed in your system. You can download and install Node.js from their official website (https://nodejs.org/en/) and MongoDB from their official website (https://www.mongodb.com/). Once you have them installed, you can proceed with the tutorial.

Step 1: Setting up a Node.js project
To begin, create a new directory for your project and navigate into it using the command line. Run the following commands to initialize a new Node.js project and install the necessary dependencies:

npm init -y
npm install express mongoose ejs

Step 2: Setting up a MongoDB database
Create a new MongoDB database by running the following command in the MongoDB shell. Replace "yourdbname" with the name of your database:

use yourdbname

Step 3: Creating a model
Create a new file called "form.js" in the root directory of your project. In this file, define a Mongoose schema for your form data. For example, a simple form schema could look like this:

const mongoose = require('mongoose');

const formSchema = new mongoose.Schema({
  name: String,
  email: String,
  message: String
});

const Form = mongoose.model('Form', formSchema);

module.exports = Form;

Step 4: Setting up Express
Create a new file called "app.js" in the root directory of your project. In this file, set up an Express server and connect it to your MongoDB database. Make sure to also set EJS as your view engine. Here is an example of how this file could look like:

const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.set('view engine', 'ejs');

mongoose.connect('mongodb://localhost/yourdbname', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('Connected to MongoDB'))
  .catch(err => console.error('Could not connect to MongoDB', err));

app.listen(3000, () => console.log('Server listening on port 3000'));

Step 5: Creating routes
In the same "app.js" file, create routes for handling form submissions and rendering form views. You can create two routes – one for rendering the form and one for submitting it. Here is an example of how these routes could look like:

app.get('/', (req, res) => {
  res.render('form');
});

app.post('/submit', async (req, res) => {
  const { name, email, message } = req.body;
  const form = new Form({
    name,
    email,
    message
  });
  await form.save();
  res.redirect('/');
});

Step 6: Creating views
Create a new directory called "views" in the root directory of your project. Inside this directory, create a new file called "form.ejs" where you can define the form markup. Here is an example of how this file could look like:

<!DOCTYPE html>
<html>
<head>
  <title>Form Submission</title>
</head>
<body>
  <form action="/submit" method="post">
    <label for="name">Name:</label>
    <input type="text" name="name" id="name" required><br>

    <label for="email">Email:</label>
    <input type="email" name="email" id="email" required><br>

    <label for="message">Message:</label>
    <textarea name="message" id="message" required></textarea><br>

    <button type="submit">Submit</button>
  </form>
</body>
</html>

Step 7: Running the application
To run the application, execute the following command in the command line from the root directory of your project:

node app.js

Visit http://localhost:3000 in your web browser to view the form. You can now submit data through the form, which will be saved to your MongoDB database.

Congratulations! You have successfully created a form using EJS, Express, and Mongoose in a Node.js environment. Feel free to customize the form and the application as per your requirements.

I hope this tutorial was helpful for you. If you have any questions or need further assistance, feel free to drop a comment below. Happy coding! 🚀

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x