Node.js is open-source and completely free—thousands of developers around the world use it daily. They use it to develop I/O intensive web applications, such as video streaming sites, single-page applications, online chat applications, and all kinds of other web apps. Built on Google Chrome's JavaScript-based runtime environment, Node.js brings plenty of advantages to the table, making it a better choice than other server-side platforms, like Java or PHP.
This Node.js MongoDB Tutorial will help you learn how to connect your webserver to a database. First, we’ll learn the basic concepts of MongoDB, and then we will create our web application. The application will enable us to add, edit, and delete students in a MongoDB database and show a list of students in the database in the browser.
MongoDB works mainly on the two following concepts:
A collection is a group of MongoDB documents; documents within a collection can contain different fields. Typically, all documents in a collection have a similar purpose.
A document is a set of key-value pairs. Documents have a dynamic schema, which means that documents in the same collection don’t need to have the same set of fields or structures. Common fields in a collection's documents may hold different types of data.
All modern applications rely on big data, fast-feature development, and flexible deployment. Traditional databases and support these requirements. Enter MongoDB.
To create a database in Node.js MongoDB:
1. Download Node.js from https://nodejs.org/en/download/. Select the installer according to your operating system and environment.
Fig: Node.js download page
2. Run the Node.js installer and accept the license agreement. You can leave other settings as default. The installer will install Node.js and prompt you to click on the finish button.
Fig: Node.js setup
3. Verify that Node.js was installed correctly by opening the command prompt and typing this command: node --version
Fig: Node.js verification
4. When we install Node.js, NPM (Node Package Manager) is also installed. NPM includes many libraries that are used in web applications, such as React. Verify whether it is installed or not with the following command in CMD: npm --version
Fig: NPM verification
Install a text editor of your choice. We are using Visual Studio Code in this tutorial, but you can also use other editors—like Atom and Sublime Text—if you are more comfortable with those.
Fig: Visual Studio Code download page
Similar to Node.js installation, you can download the MongoDB Community Server from its official website. Then, open the installer and keep the default settings to install MongoDB on your system.
Note: MongoDB Compass will also be installed in the process, which we later use to check the status of our database.
Fig: VS Code project
We are going to create our Node.js-based Student Management System. This application will enable users to connect to a MongoDB database so that they can create, update, or delete a student record as needed.
To give you an idea of what we are trying to achieve and what the project workflow should look like in advance, refer to the image below:
Create a file named server.js in the project directory. This file in our application acts as the main server—where we connect it with other files in this project.
// Node.js MongoDB server
require("./models/db");
const express = require("express");
const path = require("path");
const handleBars = require("handlebars");
const exphbs = require("express-handlebars");
const {
allowInsecurePrototypeAccess
} = require("@handlebars/allow-prototype-access");
const bodyparser = require("body-parser");
const studentController = require("./controllers/studentController");
var app = express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
app.get("/", (req, res) => {
res.send(`
<h2>Welcome to Students Database!!</h2>
<h3>Click here to get access to the <b> <ahref="/student/list">Database</a> </b></h3>`);
});
app.set("views", path.join(__dirname, "/views/"));
app.engine(
"hbs",
exphbs({
handlebars: allowInsecurePrototypeAccess(handleBars),
extname: "hbs",
defaultLayout: "mainLayout",
layoutsDir: __dirname + "/views/layouts/"
})
);
app.set("view engine", "hbs");
app.listen(3000, () => {
console.log("Express server started at port: 3000");
});
app.use("/student", studentController);
This file is used to connect the application to the MongoDB database. For this, let’s first create a folder and name it as models. Inside that folder, create a new file named db.js. There may be some items missing from the root folder—this is just a convention that web applications follow in order to increase code readability and reusability.
const mongoose = require("mongoose");
mongoose.connect(
"mongodb://localhost:27017/StudentDB",
{
useNewUrlParser: true
},
err => {
if (!err) {
console.log("Connection succeeded");
} else {
console.log("Error in connection: " + err);
}
}
);
require("./student.model");
Now, let’s define the student schema for the database in this file.
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'
},
mobile: {
type: Number,
required: 'This field is required'
},
city: {
type: String,
required: 'This field is required'
}
});
mongoose.model("Student", studentSchema);
The controller receives user requests and translates them into actions that the model should take. It then selects the appropriate view to handle the response.
Let’s create a new folder and name it controllers. Inside that folder, create a new file and name it studentController.js
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.mobile = req.body.mobile;
student.city = req.body.city;
student.save((err, doc) => {
if (!err) {
res.redirect("student/list");
} else {
console.log("Error during insert: " + err);
}
});
}
function updateRecord(req, res) {
Student.findOneAndUpdate(
{ _id: req.body._id },
req.body,
{ new: true },
(err, doc) => {
if (!err) {
res.redirect("student/list");
} else {
console.log("Error during update: " + err);
}
}
);
}
router.get("/list", (req, res) => {
Student.find((err, docs) => {
if (!err) {
res.render("student/list", {
list: docs
});
} else {
console.log("Error in retrieval: " + err);
}
});
});
router.get("/:id", (req, res) => {
Student.findById(req.params.id, (err, doc) => {
if (!err) {
res.render("student/addOrEdit", {
viewTitle: "Update Student",
student: doc
});
console.log(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 deletion: " + err);
}
});
});
module.exports = router;
An HBS file is a template that Handlebars creates, which is a web template system. In this file, we add a template written in HTML code and then embed it with Handlebars expressions.
This file will act as a layout container for the application user interface.
First, create a new folder and name it layouts. Inside that folder, create a new file and name the file mainLayout.hbs
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style>
#box {
background-color: #fff;
margin-top: 25px;
padding: 20px;
-webkit-box-shadow: 10px 10px 20px 1px rgba(0, 0, 0, 0.75);
-moz-box-shadow: 10px 10px 20px 1px rgba(0, 0, 0, 0.75);
box-shadow: 10px 10px 20px 1px rgba(0, 0, 0, 0.75);
border-radius: 10px 10px 10px 10px;
-moz-border-radius: 10px 10px 10px 10px;
-webkit-border-radius: 10px 10px 10px 10px;
border: 0px solid #000000;
}
</style>
</head>
<body class="bg-info">
<div id="box" class="col-md-6 offset-md-3" </div>
{{{body}}}
</body>
</html>
In this file, we will write the code for a form that the user can use for adding or editing a record in the database.
First, create a new folder and name it “student”. Inside that folder, create a new file and name the file addOrEdit.hbs
<h3>{{viewTitle}}</h3>
<form action="/student" method="POST" autocomplete="off">
<input type="hidden" name="_id" value="{{student._id}}">
<div class="form-group">
<label>Full Name</label>
<input type="text" class="form-control" name="fullName" placeholder="Full Name" value="{{student.fullName}}">
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" name="email" placeholder="Email" value="{{student.email}}">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Mobile</label>
<input type="text" class="form-control" name="mobile" placeholder="Mobile" value="{{student.mobile}}">
</div>
<div class="form-group col-md-6">
<label>City</label>
<input type="text" class="form-control" name="city" placeholder="City" value="{{student.city}}">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-info">Submit</button>
<a class="btn btn-secondary" href="/student/list">View All</a>
</div>
</form>
This file will display a list of all student records in the database. Inside the student folder that we created before, create a new file and name it List.hbs
<h3><a class="btn btn-secondary" href="/student">Create New</a> Students List</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Mobile</th>
<th>City</th>
<th></th>
</tr>
</thead>
<tbody>
{{#each list}}
<tr>
<td>{{this.fullName}}</td>
<td>{{this.email}}</td>
<td>{{this.mobile}}</td>
<td>{{this.city}}</td>
<td>
<a class="btn btn-primary btn-sm" href="/student/{{this._id}}">Edit</a>
<a class="btn btn-danger btn-sm" href="/student/delete/{{this._id}}"
onclick="return confirm('Are you sure you want to delete this record ?');">Delete</a>
</td>
</tr>
{{/each}}
</tbody>
</table>
Here’s how the Student Management System should look and work in the end. You are free to tweak the design of the app or add or remove features in the application.
Now that you have created a full-fledged Node.js application in this tutorial, you may be wondering how you can obtain the skills necessary to take advantage of its rising popularity. Fortunately, there are some great options to learn this exciting and practical skill set at your own pace. Simplilearn’s Node.js Certification training course will give you a great foundation in this popular platform, combining live, instructor-led training, self-paced tutorials, and hands-on projects to help you become career-ready upon completion. Get started today and seize your future!
Name | Date | Place | |
---|---|---|---|
Node.js Training | 5 Feb -5 Mar 2021, Weekdays batch | Your City | View Details |
Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.
Node.js Training
Full Stack Java Developer
*Lifetime access to high-quality, self-paced e-learning content.
Explore CategoryWhat is Node.js: A Comprehensive Guide
Understanding JWT Authentication with Node.js
Understanding Node.js Architecture
Top 48 Node.js Interview Questions and Answer
Node.js MySQL Tutorial: Create and Manage an Employee Database
Node.js Express Tutorial: Create a User Management System