Full Post Page
 

ExpressJS NodeJs Crud Part-2

Category: NODE JS & Written by Admin On May-27-2025 21:52:18

step 1 app.js //add package const express =require("express") const app =express() const mongoose=require('mongoose') const contactbfinal=require("./models/contact.models") // mongoose database connection mongoose.connect('mongodb://127.0.0.1:27017/mern-basic') .then(() =>console.log('mongoose database connection running')) //middleware app.set('view engine','ejs') app.use(express.urlencoded({ extended:false})) // for form data app.use(express.static('public')) // for use css create public folder for attached css files // 7 route one testing app.get('/testing',(req,res)=>{ res.send("<h2>Testing page</h2>") //print test res.render("testing") // print html page }) // step 1 all record app.get('/',async(req,res)=>{ const fetall=await contactbfinal.find() //db.tablename.find() no need db // res.json(fetall) // for showing json // res.render('home') // res.render('home' ,{fetchalldata:fetall}) // 'html page',{first key ,fetvar} res.render('home' ,{fetall:fetall}) }) // step 2. singale data fetching app.get('/show-contact/:id',async(req,res)=>{ /*agar route se id use krte hai request method param use krenge //const fetchsingle=await contactbfinal.findOne({ _id:req.params.id}) //upar route value ke lene ke lie param use kie method 1 method 2 finaltablenme.findByID(req,param.id) */ const fetchsingle=await contactbfinal.findById(req.params.id) // res.json(fetchsingle) // show data single in json res.render('show-contact',{fetchsingle:fetchsingle}) }) app.get('/add-contact',(req,res)=>{ res.render('add-contact') })// insert open from //INSERT save // post route run after submit app.post('/add-contact',async(req,res)=>{ const inQuery=await contactbfinal.insertOne({ // fistdatabse:req.body.form input name method 1 first_name: req.body.firstName, last_name: req.body.lastName, email: req.body.email, phone: req.body.phone, address: req.body.address }) res.redirect('/') }) // EDIT //update page open edit /app.get('/update-contact/:id',async(req,res)=>{ const Editdata=await contactbfinal.findById(req.params.id) // res.json(fetchsingle) // show data single in json res.render('update-contact',{Editdata:Editdata}) // res.render('update-contact') }) //UPDATE app.post('/update-contact/:id',async(req,res)=>{ try { const {first_name,last_name,email,phone,address} = req.body await contactbfinal.findByIdAndUpdate(req.params.id,{ first_name: req.body.firstName, last_name: req.body.lastName, email: req.body.email, phone: req.body.phone, address: req.body.address }) res.redirect('/') } catch (err) { console.error(err); res.status(500).send('Update failed'); } }); app.get('/delete-contact/:id',async(req,res)=>{ await contactbfinal.findByIdAndDelete(req.params.id) res.redirect('/') }) //server app.listen(3000,()=>{ console.log("Server started Successfully on port 3000.") }) step 2 Model folder contactbfinal.model.js const mongoose=require('mongoose') // add mongoose package add also index.js const ContactSchemafd=mongoose.Schema({ first_name:{ type:String }, last_name:{ type:String }, email:{ type:String }, phone:{ type:String }, address:{ type:String } }) // ab ye schema kaun sa collection (table) me lena hai using . // mongoose.model(collection_nameself,YourSchemaname) const contacttblefd =mongoose.model("Contactble",ContactSchemafd) //exports aslo app.js module.exports=contacttblefd Home.ejs <%- include('common-contact/header.ejs') %> <div class="ml-auto"> <a href="/add-contact" class="btn btn-success me-2"><i class="fa fa-plus-circle"></i> Add New</a> </div> <div class="table-responsive"> <table class="table table-striped table-bordered align-middle"> <thead class="table-dark"> <tr> <th>#</th> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Phone</th> <th>Address</th> <th>Opration</th> </tr> </thead> <tbody> <% let sr=1; fetall.forEach(value => { %> <tr> <td> <%= sr++ %> </td> <td> <%=value.first_name %> </td> <td> <%=value.last_name %> </td> <td> <%=value.email %> </td> <td> <%=value.phone %> </td> <td> <%=value.address %> </td> <td width="150"> <a href="/show-contact/<%=value._id %>" class="btn btn-sm btn-circle btn-outline-info" title="Show"><i class="fa fa-eye"></i></a> <a href="/update-contact/<%=value.id %>" class="btn btn-sm btn-circle btn-outline-secondary" title="update"><i class="fa fa-edit"></i></a> <a href="/delete-contact/<%=value.id %> " class="btn btn-sm btn-circle btn-outline-danger" title="Delete" onclick="confirm('Are you sure?')"><i class="fa fa-times"></i></a> </td> </tr> <% }); %> <!-- Add more rows as needed --> </tbody> </table> </div> </div> <%- include('common-contact/footer.ejs') %> contact-update.ejs <%- include('common-contact/header.ejs') %> <div class="contact-box"> <!-- <h3 class="text-center mb-4">update Contact Form</h3> --> <div class="d-flex justify-content-between align-items-center mb-4"> <h2 class="text-primary">update-contacts</h2> <div> <form action="/update-contact/<%= Editdata.id %>" method="POST"> <div class="row g-3"> <div class="col-md-6"> <label for="firstName" class="form-label">First Name</label> <input type="text" class="form-control" value="<%= Editdata.first_name%>" name="firstName" placeholder="John" required /> </div> <div class="col-md-6"> <label for="lastName" class="form-label">Last Name</label> <input type="text" class="form-control"value="<%= Editdata.last_name%>" name="lastName" placeholder="Doe" required /> </div> <div class="col-md-6"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" value="<%= Editdata.email%>" name="email" placeholder="john@example.com" required /> </div> <div class="col-md-6"> <label for="phone" class="form-label">Phone</label> <input type="tel" class="form-control" value="<%= Editdata.phone%> name="phone" placeholder="+91 1234567890" required /> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <textarea class="form-control" name="address" rows="3" placeholder="123 Street Name, City" required> <%= Editdata.address%></textarea> </div> </div> <div class="mt-4 d-flex justify-content-between"> <button type="submit" class="btn btn-success">update</button> <!-- <button type="reset" class="btn btn-outline-secondary">Cancel</button> --> <a href="/" class="btn btn-outline-secondary">Cancel</a> </div> </form>

Comments

Share your thoughts about this post

Why Choose Us:

Experienced Instructors: Our team of experienced instructors are passionate about coding and dedicated to helping you succeed. With years of industry experience and a knack for teaching, they'll guide you every step of the way. Beginner-Friendly Content: Don't worry if you're new to coding. Our tutorials are designed with beginners in mind, starting from the fundamentals and gradually building up to more advanced topics. Updated Content: Coding is a rapidly evolving field, and we're committed to keeping our content up-to-date with the latest trends, technologies, and best practices. Community Support: Learning to code is more fun and effective when you're part of a supportive community. Join our online community forums to connect with fellow learners, share insights, and collaborate on projects. Get Started Today:



Recent Posts

Advance Js Fetch API Part-5

June-06-2025 21:23:08


Advance Js Promise Part-4

June-06-2025 11:35:05


Advance js oop part-3

June-06-2025 08:25:42


ExpressJs API With Image Crud-3

June-02-2025 21:09:41


NodeJs API-MVC-2

June-02-2025 10:56:22


ExpressJs API Crud-1

June-02-2025 10:27:58


ExpressJs Files upload

June-02-2025 10:15:40


NodeJS Cookie and CsrfToken

May-30-2025 19:20:40


ExpressJS Session

May-30-2025 19:14:29


ExpressJS NodeJs Crud Part-2

May-27-2025 21:52:18


ExpressJS NodeJS Crud Part-1

May-27-2025 21:33:30


ExpressJS Authentication

May-26-2025 17:11:41


NodeJS ExpressJS Files Upload

May-26-2025 16:53:29



Angular Introduction

May-13-2025 21:02:32



Advance Js part-1

May-12-2025 15:41:29