How to Connect MongoDB with Express
How to Connect MongoDB with Express?
- MongoDB is an open-source document database and a leading NoSQL database.
- MongoDB is written in C++.
- Download MongoDB Community Server in your system using the link
- Install the MongoDB in your system
- To Download and install the MongoDB module, open the command Terminal and execute the following:
npm install mongoose
Create Connection
- In MongoDB Create a Database with the name StudentDB
- Create a folder and open VS code and run the command on terminal
npm init
- install few packages
npm i --save express mongoose body-parser express-handlebars
- Now create a new file and folder which are required
- For connection between express and MongoDB In the model's folder db.js:
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/StudentDB',{useNewUrlParser:true},(err)=>{
if(!err){
console.log('mongoDB Connection succeeded')
}
else{
console.log('Error in mongoDB Connection :'+err)
}
});
- For starting the server code in the server.js:
require('./models/db');
const express=require('express');
var app=express();
app.listen(3000,()=>{
console.log('Express server started at port:3000')
})
- Save the code and run the file:
node server.js
- Output in terminal:
Thus, Connection is successful.
Crud operation
After connection with MongoDB, Let's begin with crud operations like add, delete, update and get.
- Now create a new file and folder which are required
- Let's begin with models or Attributes want to use and further store in the database. In student.model.js:
const mongoose=require('mongoose');
var studentSchema= new mongoose.Schema({
fullName:{
type:String,
required: 'This field is required.'
},
email:{
type:String,
required: 'This field is required.'
},
enrollmentnumber:{
type:String,
},
});
#validate for correct email
studentSchema.path('email').validate((val) => {
emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailRegex.test(val);
}, 'Invalid e-mail.');
mongoose.model('Student',studentSchema);
- for the main or first page frontend create a file mainLayout.hbs
<!DOCTYPE html>
<html>
<head>
<title>Node.js express mongDB CRUD</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body class="bg-info">
<div class="row">
<div class="col-md-6 offset-md-3" style="background-color: #fff;margin-top: 25px;padding:20px;">
{{{body}}}
</div>
</div>
</body>
</html>
- further frontend in list.hbs and addorEdit.hbs respectively.
<h3><a class="btn btn-secondary" href="/student"><i class="fa fa-plus"></i> Create New</a> student List</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Enrollment Number</th>
</tr>
</thead>
<tbody>
{{#each list}}
<tr>
<td>{{this.fullName}}</td>
<td>{{this.email}}</td>
<td>{{this.enrollmentnumber}}</td>
<td>
<a href="/student/{{this._id}}"><i class="fa fa-pencil fa-lg" aria-hidden="true"></i></a>
<a href="/student/delete/{{this._id}}" onclick="return confirm('Are you sure to delete this record ?');"><i class="fa fa-trash fa-lg" aria-hidden="true"></i></a>
</td>
</tr>
{{/each}}
</tbody>
</table>
<h3>{{viewTitle}}</h3>
<form action="/student" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{s._id}}">
<div class="form-group">
<label>Full Name</label>
<input type="text" class="form-control" name="fullName" placeholder="Full Name" value="{{student.fullName}}">
<div class="text-danger">
{{student.fullNameError}}</div>
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" placeholder="Email" value="{{student.email}}">
<div class="text-danger">
{{student.emailError}}</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Enrollment Number</label>
<input type="text" class="form-control" name="rollno" placeholder="Enrollment number" value="{{student.enrollmentnumber}}">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info"><i class="fa fa-database"></i> Submit</button>
<a class="btn btn-secondary" href="/student/list"><i class="fa fa-list-alt"></i> View All</a>
</div>
</form>
- In studentController.js, all the crud operations functions are in the below code:
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Student = mongoose.model('Student');
router.get('/', (req, res) => {
res.render("student/addOrEdit", {
viewTitle: "Insert student"
});
});
router.post('/', (req, res) => {
if (req.body._id == '')
insertRecord(req, res);
else
updateRecord(req, res);
});
function insertRecord(req, res) {
var student = new Student();
student.fullName = req.body.fullName;
student.email = req.body.email;
student.enrollmentnumber = req.body.enrollmentnumber;
student.save((err, doc) => {
if (!err)
res.redirect('student/list');
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("student/addOrEdit", {
viewTitle: "Insert student Details",
student: req.body
});
}
else
console.log('Error during record insertion : ' + err);
}
});
}
function updateRecord(req, res) {
Student.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
if (!err) {
res.redirect('student/list');
}
else {
if (err.name == 'ValidationError') {
handleValidationError(err, req.body);
res.render("student/addOrEdit", {
viewTitle: 'Update student',
student: req.body
});
}
else
console.log('Error during record update : ' + err);
}
});
}
router.get('/list', (req, res) => {
// res.json('from list')
Student.find((err, docs) => {
if (!err) {
res.render("student/list", {
list: docs
});
}
else {
console.log('Error in retrieving student 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) => {
Student.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("student/addOrEdit", {
viewTitle: "Update student",
student: doc
});
}
});
});
router.get('/delete/:id', (req, res) => {
Student.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/student/list');
}
else { console.log('Error in student delete :' + err); }
});
});
module.exports = router;
- In server.js, install handlebars/allow-prototype-access
npm i @handlebars/allow-prototype-access
require('./models/db');
const express=require('express');
const path=require('path');
const exphbs=require('express-handlebars');
const bodyparser = require('body-parser');
const Handlebars = require('handlebars')
const {allowInsecurePrototypeAccess} = require('@handlebars/allow-prototype-access')
const studentController=require('./controllers/studentController');
var app=express();
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.set('views',path.join(__dirname,'/views/'));
app.engine('hbs', exphbs.engine({ extname: 'hbs',handlebars: allowInsecurePrototypeAccess(Handlebars), defaultLayout: 'mainLayouts', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine','hbs');
app.listen(3000,()=>{
console.log('Express server started at port:3000')
});
app.use('/student',studentController);
- Run the server and open the local host on port:http://localhost:3000/student
- Main layout
- Add data
If data is inappropriate it will show the error:
- Table format
- On clicking on the delete button shown in the above image, an alert box pop up, and click on Ok if you are sure to delete the record.
- After all the operations are done, Once observe the change in the database too.