Getting Started With NodeJs MongoDB

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

  • 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 official 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 fields. 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 fields or structures. Common fields in a collection's documents may hold different types of data.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Why connect Node.js with MongoDB?

All modern applications rely on big data, fast-feature development, and flexible 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

var-mongo

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 finish button.

node-js-setup

Fig: Node.js setup

3. Verify that Node.js was installed correctly by opening the command prompt and typing this command: node --version

/node-jsverification

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

npm-veri.

Fig: NPM verification

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.

visual-code

Fig: Visual Studio Code download page

MongoDB Installation

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.

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.

vs code

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 workflow should look like in advance, refer to the image below: 

mongodb-crud

Components

server.js

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 serverrequire("./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

vs code2

  • 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 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");
  • Let’s first install the mongoose module using the terminal that VSCode provides, the same way we did before for the server.js file
  • 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 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);
  • First, import the mongoose module in the file
  • Create a variable and name it studentSchema
  • Then, use the mongoose.Schema() method and define the required fields to add the data to the database
  • Set the model “Student” to studentSchema

Learn Essential Skills for Effective Leadership

Executive Leadership Principles ProgramExplore Program
Learn Essential Skills for Effective Leadership

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 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;
  • Let’s first import the required modules for this file, 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
  • Define a function insertRecord(), to add the records into the database
  • Define 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 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>
  • 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 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 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 file, we create a basic HTML form with all the input fields 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

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

List.hbs

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>&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 confirm('Are you sure you want to delete this record ?');">Delete</a>            </td>        </tr>        {{/each}}    </tbody></table>
  • In this file, 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.

Get Ahead of the Curve and Master Node.js Today

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 Full Stack Developer - MERN Stack 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!

About the Author

Taha SufiyanTaha Sufiyan

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.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.