Today In This Tutorials we are Going to Learn How to send data from html to MongoDB Using Express Js
In This Tutorial we will Create Simple HTML Form That Will Save User Data To Server Using Node Js with MongoDB DataBase
Prerequisites
You Should Have MongoDB Compass Installed in Your System if you Haven't install Yet Install MongoDB from Here
Now Install All This Dependencies Using Terminal
Install Required Package
Mongoose
Express Js
Body- Parser
Make a Folder naming Registration and Use The Following Command to Install the Above Package in your Folder Using Windows Terminal or Using VS Code Terminal
npm init -y npm i --save express npm i body-parser npm i mongoose
Now i am going to Write server.Js Code in part wise so that it will be Easy to Understand.
Importing All Require Package
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const port = 2000; const path = require('path');
const publicPath = path.join(__dirname,) app.use(bodyParser.urlencoded({ extended: true }));
Make a Express Serves and Check Weather it is running or Not. for this I am Taking PORT:2000 You can Take Your own if needed. You Can Check Your Server running by using This Url: localhost:2000
app.listen(port, (err) => {
if (err) {
console.log(err);
} else {
console.log("Server is running on port", port)
}
})
Connecting MongoDB with Node js express Locally
mongoose.connect('mongodb://localhost:27017/employee')
.then(() => {
console.log("Database Connected")
}).catch((err) => {
console.log("Error in Database", err);
})
Creating DataBase Schema to Store Data In MongoDB
const employeeSchema = {
firstName: 'String',
lastName: 'String',
email: 'String',
position: 'String',
salary: 'Number',
lastCompany: 'String',
Mobileno: 'Number',
Comments: 'String',
date: 'date'
}
const detail = mongoose.model("detail", employeeSchema);
app.get('/', (req, res) => {
res.sendFile(`${publicPath}/index.html`);
})
Fetching Value From HTMl Form body Into MongoDB DataBase
app.post("/", function (req, res) {
let newDetails = new detail({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
position: req.body.position,
salary: req.body.salary,
lastCompany: req.body.salary,
Mobileno: req.body.Mobileno,
Comments: req.body.Comments,
date: req.body.date
});
newDetails.save();
res.redirect("./");
})
To Fill the Data Here are the HTML Form Table Code
Index.HTML
<!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>Document</title>
</head>
<body>
<form action="/" id="EmploymentApplication100" method="post">
<table border="0" cellpadding="5" cellspacing="0">
<tr>
<td style="width: 50%">
<label for="First_Name"><b>First name *</b></label><br />
<input name="firstName" type="text" maxlength="50" style="width:100%;max-width: 260px"
required=" " />
</td>
<td style="width: 50%">
<label for="Last_Name"><b>Last name *</b></label><br />
<input name="lastName" type="text" maxlength="50" style="width:100%;max-width: 260px" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="Email_Address"><b>Email *</b></label><br />
<input name="email" type="text" maxlength="100" required=" " style="width:100%;max-width: 535px" />
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2">
<label for="Position"><b>Position you are applying for *</b></label><br />
<input name="position" type="text" maxlength="100" style="width:100%;max-width: 535px" />
</td>
</tr>
<tr>
<td>
<label for="Salary"><b>Salary requirements</b></label><br /> <input name="salary" type="text"
maxlength="50" style="width:100%;max-width: 260px" />
</td>
<td>
</td>
</tr>
<tr>
<td>
<label for="Phone"><b>Phone *</b></label><br />
<input name="Mobileno" type="text" maxlength="50" style="width:100%;max-width: 260px" />
</td>
<td>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2">
<label for="Organization"><b>Last company you worked for</b></label><br />
<input name="lastCompany" type="text" maxlength="100" style="width:100%;max-width: 535px" />
</td>
</tr>
<tr>
<td colspan="2">
<label for="Reference"><b>Reference / Comments / Questions</b></label><br />
<textarea name="Comments" rows="7" cols="40" style="width:100%;max-width: 535px"></textarea>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;">
<input name="skip_submit" type="submit" value="Send Application" />
</td>
</tr>
</table>
</form>
</body>
</html>
Paste The Below Code in Server.Js File
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const port = 2000; const path = require('path'); const publicPath = path.join(__dirname,) app.use(bodyParser.urlencoded({ extended: true })); //Database Connection mongoose.connect('mongodb://localhost:27017/employee') .then(() => { console.log("Database Connected") }).catch((err) => { console.log("Error in Database", err); }) //Creation Data Schema const employeeSchema = { firstName: 'String', lastName: 'String', email: 'String', position: 'String', salary: 'Number', lastCompany: 'String', Mobileno: 'Number', Comments: 'String', date: 'date' } const detail = mongoose.model("detail", employeeSchema); app.get('/', (req, res) => { res.sendFile(`${publicPath}/index.html`); }) app.post("/", function (req, res) { let newDetails = new detail({ firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, position: req.body.position, salary: req.body.salary, lastCompany: req.body.salary, Mobileno: req.body.Mobileno, Comments: req.body.Comments, date: req.body.date }); newDetails.save(); res.redirect("./"); }) app.listen(port, (err) => { if (err) { console.log(err); } else { console.log("Server is running on port", port) } })
If you Face Any Problems or Error while Insert data in MongoDB from HTML form Comment Down Below to get your queries Solved.
Tags:
Project