Node JS Tutorial in Hindi #48 | REST API with Node.js & MongoDB | Save Form Data in MongoDB

Save data with Form in MongoDB


  1. Make html form
  2. Make route to handle post request
  3. Write code to add data in mongoDB
  4. Test code and flow

Git link for code https://github.com/anil-sidhu/node-express-mongodb/tree/add-data-in-mongodb


index.js code


import express from 'express'
import { MongoClient } from 'mongodb';

const dbName="school"
const url ="mongodb://localhost:27017"
const client= new MongoClient(url)

const app = express();
app.use(express.urlencoded({extended:true}))
app.use(express.json());

app.set("view engine",'ejs')
client.connect().then((connection)=>{
const db =connection.db(dbName);

app.get("/api",async (req,resp)=>{
const collection =db.collection("students")
const students= await collection.find().toArray();
resp.send(students)
})
app.get("/ui",async (req,resp)=>{
const collection =db.collection("students")
const students= await collection.find().toArray();
resp.render('students',{students})
})

app.get('/add',(req,resp)=>{
resp.render('add-student')
})

app.post("/add-student",async (req,resp)=>{
// console.log(req.body);
const collection =db.collection("students")
const result= await collection.insertOne(req.body)
console.log(result);
// const students= await collection.find().toArray();
resp.send("data saved")
})

app.post("/add-student-api",async(req,resp)=>{
console.log(req.body);
const {name,age,email}= req.body;
if(!name || !age || !email){
resp.send({message:"operation failed",success:false})
return false
}
const collection = db.collection("students");
const result = await collection.insertOne(req.body)
resp.send({message:"data stored",success:true,result:result})
})

})

// app.set("view engine",'ejs')

app.listen(3200)



views/students.ejs


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Data will be here</h1>

<table border="1">
<tr>
<td>Name</td>
<td>Age</td>
<td>Email</td>
</tr>

<% students.forEach(student=>{ %>
<tr>
<td><%= student.name %></td>
<td><%= student.age %></td>
<td><%= student.email %></td>
</tr>
<% }) %>
</table>
</body>
</html>


views/add-student.ejs


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Students</title>
</head>
<body>
<form method="post" action="add-student">
<input type="text" name="name" placeholder="enter student name" />
<br/><br/>
<input type="text" name="email" placeholder="enter student email" />
<br/><br/>
<input type="text" name="age" placeholder="enter student age" />
<br/><br/>
<button>Add new Student</button>
</form>
</body>
</html>