I'm trying to validate the uniqueness of the Email ID, when a user enters the duplicate email ID it should show the warning.
Is there any way to get the desired output?
I've tried the below condition, but it won't show the warning in the browser.
email: {
type: String,
unique : true
}
const mongoose = require('mongoose');
var employeeSchema = new mongoose.Schema({
fullName: {
type: String,
required: 'This field is required.'
},
email: {
type: String,
unique : true
},
mobile: {
type: String
},
city: {
type: String
}
});
mongoose.model('Employee', employeeSchema);
The below code snippet belongs to "employeeController.js" File
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');
router.get('/', (req, res) => {
res.render("employee/addOrEdit", {
viewTitle: "Insert Employee"
});
});
router.post('/', (req, res) => {
if (req.body._id == '')
insertRecord(req, res);
else
updateRecord(req, res);
});
function insertRecord(req, res) {
var employee = new Employee();
employee.fullName = req.body.fullName;
employee.email = req.body.email;
employee.mobile = req.body.mobile;
employee.city = req.body.city;
employee.save((err, doc) => {
if (!err)
res.redirect('employee/list');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("employee/addOrEdit", {
viewTitle: "Insert Employee",
employee: req.body
});
}
else
console.log('Error during record insertion : ' + 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;
}
}
}
module.exports = router;