[go: up one dir, main page]

0% found this document useful (0 votes)
13 views18 pages

Nodejs-04-Getting Started With NodeJs MongoDB

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 18

Getting Started With NodeJs MongoDB

Lesson 4 of 9 By Taha Su�yan

Last updated on Feb 20, 2023 58275

Previous Next

Tutorial Playlist

Table of Contents

What is MongoDB?

Why connect Node.js with MongoDB?

Create a MongoDB Database in Node.js

Build a Student Management System

Let’s Code Now!

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

• It is a NoSQL database and is written in C++

• To be able to use MongoDB, download the free MongoDB database from the o�cial website

MongoDB works mainly on the two following concepts:

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.

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development

EXPLORE PROGRAM

Why connect Node.js with MongoDB?

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

To create a database in Node.js MongoDB:

• Start by creating a MongoClient object

• Specify a connection URL with the correct IP address and the name of the database you want to create

Build a Student Management System

Node.js Installation

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 �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

Fig: Node.js veri�cation

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 veri�cation

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

1. Create an empty folder and name it as mongodb_crud.

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.

Fig: VS Code project

Let’s Code Now!

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.

// 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);

• Import database from models folder

• Import some modules that are required in the application: express, path, handlebars, express-handlebars, body-
parser, and @handlebars/allow-prototype-access

• Add these modules using the terminal inside VSCode


• After that, we use bodyparser to parse JSON in the HTTP request

• 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.

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");

• 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:

• Add the URL for the database

• 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.

const mongoose = require("mongoose");

var studentSchema = new mongoose.Schema({

fullName: {

type: String,

required: 'This �eld is required'

},

email: {

type: String,

required: 'This �eld is required'

},

mobile: {

type: Number,

required: 'This �eld is required'

},

city: {

type: String,

required: 'This �eld is required'

}
});

mongoose.model("Student", studentSchema);

• First, import the mongoose module in the �le

• Create a variable and name it studentSchema

• Then, use the mongoose.Schema() method and de�ne the required �elds to add the data to the database

• Set the model “Student” to studentSchema

Learn Essential Skills for Effective Leadership

Executive Leadership Principles Program

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

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) => {


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.�ndOneAndUpdate(
Student.�ndOneAndUpdate(

{ _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.�nd((err, docs) => {

if (!err) {

res.render("student/list", {

list: docs

});

} else {

console.log("Error in retrieval: " + err);

});

});
});

router.get("/:id", (req, res) => {

Student.�ndById(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.�ndByIdAndRemove(req.params.id, (err, doc) => {

if (!err) {

res.redirect("/student/list");

} else {

console.log("Error in deletion: " + err);

});

});

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

• Student (we just created this model)

• 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

• router.post() to allow a user to add or update records into the database

• De�ne a function insertRecord(), to add the records into the database

• De�ne a function updateRecord(), to update the records in the database

• 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>

<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>

• 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

• {{{body}}} is a Handlebars expression that contains the elements in the page

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>

<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 �le creates the form that is rendered on screen

• 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

Basics to Advanced - Learn It All!

Caltech PGP Full Stack Development

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

<h3><a class="btn btn-secondary" href="/student">Create


New</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;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 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.

You might also like