-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
87 lines (58 loc) · 1.88 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const express = require('express');
const app = express();
exports.app = app;
const path = require('path');
const UserModel = require('./models/user.js');
app.use(express.json());
app.use(express.urlencoded({ extended:true }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.get('/', (req, res) => {
res.render('index',)
});
app.get('/viewusers', async (req, res) => {
try {
let user = await UserModel.find();
// console.log(user); //debugging checks
res.render('users', { user });
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/delete/:id', async (req, res) => {
try {
console.log(req.params.id); // Logging the ID to check
// Use findOneAndDelete with a condition
const user = await UserModel.findOneAndDelete({ _id: req.params.id });
console.log("User deleted:", user);
res.redirect('/viewusers');
} catch (err) {
console.error("Error deleting user:", err);
res.status(500).send("Error deleting user");
}
});
app.get('/edit/:userid', async (req,res)=>{
let user = await UserModel.findOne({_id:req.params.userid})
console.log(user.name)
res.render('edit',{user:user});
})
app.post('/create', async (req, res) => {
let {name , email,image}=req.body;
await UserModel.create({name,email,image})
res.redirect('/viewusers');
})
app.post('/update/:userid', async (req, res)=> {
try{
let {name,email,image}=req.body;
let user=await UserModel.findOneAndUpdate({_id:req.params.userid},{name,email,image},{new:true});
console.log(user);
res.redirect('/viewusers');
}
catch(err){
console.log(err);
}
})
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});