Nodejs-04-Getting Started With NodeJs MongoDB
Nodejs-04-Getting Started With NodeJs MongoDB
Nodejs-04-Getting Started With NodeJs MongoDB
Previous Next
Tutorial Playlist
Table of Contents
What is MongoDB?
View More
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.
What is MongoDB?
• MongoDB is a cross-platform, document-oriented database that provides high performance and scalability. It
works on the concepts of collection and document
• To be able to use MongoDB, download the free MongoDB database from the o�cial website
Collection
A collection is a group of MongoDB documents; documents within a collection can contain different �elds.
Typically, all documents in a collection have a similar purpose.
Document
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 �elds or structures. Common �elds in a collection's documents
may hold different types of data.
EXPLORE PROGRAM
All modern applications rely on big data, fast-feature development, and �exible deployment. Traditional databases
and support these requirements. Enter MongoDB.
Create a MongoDB Database in Node.js
• Specify a connection URL with the correct IP address and the name of the database you want to create
Node.js Installation
1. Download Node.js from https://nodejs.org/en/download/. Select the installer according to your operating system
and environment.
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 �nish button.
Fig: Node.js setup
3. Verify that Node.js was installed correctly by opening the command prompt and typing this command: node
--version
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
Text Editor
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
MongoDB Installation
Similar to Node.js installation, you can download the MongoDB Community Server from its o�cial 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.
Project Setup
2. Open the newly created directory in VS Code and inside the terminal, and type npm init to initialize the project.
Press Enter to leave the default settings as they are.
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 work�ow should look like in advance, refer
to the image below:
Components
server.js
Create a �le named server.js in the project directory. This �le in our application acts as the main server—where we
connect it with other �les in this project.
require("./models/db");
const {
allowInsecurePrototypeAccess
} = require("@handlebars/allow-prototype-access");
app.use(bodyparser.json());
app.get("/", (req, res) => {
res.send(`
});
app.engine(
"hbs",
exphbs({
handlebars: allowInsecurePrototypeAccess(handleBars),
extname: "hbs",
defaultLayout: "mainLayout",
})
);
app.listen(3000, () => {
});
app.use("/student", studentController);
• Import some modules that are required in the application: express, path, handlebars, express-handlebars, body-
parser, and @handlebars/allow-prototype-access
• Then we use app.get() to redirect the user to localhost:3000/student/list to view the content in the student
database
• Let’s then set the views directory in which we will write the code for the user interface—in our case, the
handlebars template (that’s why the view engine is set to hbs)
• Lastly, set the server to listen at port 3000 and use studentController, which we will create later in the project
db.js
This �le is used to connect the application to the MongoDB database. For this, let’s �rst create a folder and name it
as models. Inside that folder, create a new �le 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.
mongoose.connect(
"mongodb://localhost:27017/StudentDB",
useNewUrlParser: true
},
err => {
if (!err) {
console.log("Connection succeeded");
} else {
);
require("./student.model");
• Let’s �rst install the mongoose module using the terminal that VSCode provides, the same way we did before for
the server.js �le
• After that, use the connect() method to connect to the MongoDB database. To do so, you’ll want to take the
following steps:
• Write an error callback function to handle any exceptions that might occur
student.model.js
Now, let’s de�ne the student schema for the database in this �le.
fullName: {
type: String,
},
email: {
type: String,
},
mobile: {
type: Number,
},
city: {
type: String,
}
});
mongoose.model("Student", studentSchema);
• Then, use the mongoose.Schema() method and de�ne the required �elds to add the data to the database
EXPLORE PROGRAM
studentController.js
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 �le and name it
studentController.js
res.render("student/addOrEdit", {
});
});
if (req.body._id == "") {
insertRecord(req, res);
} else {
updateRecord(req, res);
});
student.fullName = req.body.fullName;
student.email = req.body.email;
student.mobile = req.body.mobile;
student.city = req.body.city;
if (!err) {
res.redirect("student/list");
} else {
});
Student.�ndOneAndUpdate(
Student.�ndOneAndUpdate(
{ _id: req.body._id },
req.body,
{ new: true },
if (!err) {
res.redirect("student/list");
} else {
);
if (!err) {
res.render("student/list", {
list: docs
});
} else {
});
});
});
if (!err) {
res.render("student/addOrEdit", {
student: doc
});
console.log(doc);
});
});
if (!err) {
res.redirect("/student/list");
} else {
});
});
module.exports = router;
• Let’s �rst import the required modules for this �le, which are:
• Let’s �rst import the required modules for this �le, which are:
• express
• mongoose
• Now, add multiple routes for the user to be able to view and perform multiple operations
• router.get() to enable a user to add or edit a student in the database. This router will render a UI for adding or
editing a user; the UI will be added later in the project
• Add a new GET route to retrieve the list of records from the database
• Finally, add two more GET routes, which will update the records and delete them from the database
mainLayout.hbs
An HBS �le is a template that Handlebars creates, which is a web template system. In this �le, we add a template
written in HTML code and then embed it with Handlebars expressions.
This �le 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 �le and name the �le mainLayout.hbs
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous">
<style>
#box {
background-color: #fff;
margin-top: 25px;
padding: 20px;
</style>
</head>
<body class="bg-info">
{{{body}}}
</body>
</html>
• Add a basic HTML skeleton code to show the data in the form of a box
• To make the design look good, use Bootstrap CSS to style the elements
• Then, add the relevant styles to the div tag to make it look like a fancy box with shadows
addOrEdit.hbs
In this �le, 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 �le and name the �le addOrEdit.hbs
<h3>{{viewTitle}}</h3>
<div class="form-group">
<label>Full Name</label>
</div>
<div class="form-group">
<label>Email</label>
</div>
<div class="form-row">
<label>Mobile</label>
</div>
<label>City</label>
</div>
</div>
<div class="form-group">
</div>
</form>
• This form is for the user to add or update a record in the database
• In this particular �le, we create a basic HTML form with all the input �elds that are required
• Finally, let’s add a couple of buttons. One for submitting the form, and another for going back to the student list
without manipulating the data
EXPLORE PROGRAM
List.hbs
This �le will display a list of all student records in the database. Inside the student folder that we created before,
create a new �le and name it List.hbs
<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>
onclick="return con�rm('Are you sure you want to delete this record ?');">Delete</a>
</td>
</tr>
{{/each}}
</tbody>
</table>
• In this �le, we create a simple HTML table to show the student records in a tabular format
• The syntax enclosed in these braces {{}} is a Handlebars expression that fetches the list and displays it in the
web browser
Final Result
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.