-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatientController.js
More file actions
109 lines (97 loc) · 2.94 KB
/
patientController.js
File metadata and controls
109 lines (97 loc) · 2.94 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Patient = mongoose.model('Patient');
router.get('/', (req, res) => {
res.render("patient/addOrEdit", {
viewTitle: "Patient"
});
});
router.post('/', (req, res) => {
if (req.body._id == '')
insertRecord(req, res);
else
updateRecord(req, res);
});
function insertRecord(req, res) {
var patient = new Patient();
patient.fullName = req.body.fullName;
patient.email = req.body.email;
patient.mobile = req.body.mobile;
patient.save((err, doc) => {
if (!err)
res.redirect('patient/list');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("patient/addOrEdit", {
viewTitle: "Insert patient",
patient: req.body
});
}
else
console.log('Error during record insertion : ' + err);
}
});
}
function updateRecord(req, res) {
Patient.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
if (!err) { res.redirect('patient/list'); }
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("patient/addOrEdit", {
viewTitle: 'Update patient',
patient: req.body
});
}
else
console.log('Error during record update : ' + err);
}
});
}
router.get('/list', (req, res) => {
Patient.find((err, docs) => {
if (!err) {
res.render("patient/list", {
list: docs
});
}
else {
console.log('Error in retrieving patient list :' + err);
}
});
});
function handleValidationError(err, body) {
for (field in err.errors) {
switch (err.errors[field].path) {
case 'fullName':
body['fullNameError'] = err.errors[field].message;
break;
case 'email':
body['emailError'] = err.errors[field].message;
break;
default:
break;
}
}
}
router.get('/:id', (req, res) => {
Patient.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("patient/addOrEdit", {
viewTitle: "Update patient",
patient: doc
});
}
});
});
router.get('/delete/:id', (req, res) => {
Patient.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/patient/list');
}
else { console.log('Error in patient delete :' + err); }
});
});
module.exports = router;