JavaScript

Node.js and MongoDB Tutorial

Hello. In this tutorial, we will create a simple node.js application and perform the CRUD operations with the MongoDB.

The node.js framework is commonly used to create server-based applications which are further used to show the contents to the users. 

1. Introduction

Let us first understand that what is Mongo database and set up Node.js.

  • MongoDB is a high-performance NoSQL database where each database has collections that in turn have documents. Each document has a different number of fields, size, content, and is stored in a JSON-like format (i.e. Binary JSON (BSN)
  • The documents in MongoDB don’t need to have a schema defined beforehand. Instead, the fields (i.e. records) can be created on the go
  • Data model available within the MongoDB allows developers to represent the hierarchical relationships, store arrays, and other more complex structures easily
  • This NoSQL solution often comes with embedding, auto-sharding, and onboard replication for better scalability and high availability

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

node js mongo db tutorial - npm intallation
Fig. 1: Verifying node and npm installation

2. Setting up Mongo database on Docker

To start with the tutorial, I am hoping that you have the Mongo database up and running in your local environment. For easy use, I will set it up in the Docker environment. You can use the below manifest file to get the container up and running in minutes. The file will also create an initial database named employeedb.

stack.yml

services:
  mongodb:
    image: mongo
    container_name: mongodb
    environment:
      MONGO_INITDB_DATABASE: employeedb
    ports:
      - "27017:27017"
version: "3"

To execute or stop/remove the manifest file you can execute the below commands.

Docker commands

-- start the container
docker-compose -f stack.yml up -d

-- stop and remove the container
docker-compose -f stack.yml down

If everything goes well the container would be started successfully as shown in Fig. 2 and you can use the docker ps -a command to confirm.

node js mongo db tutorial - container status
Fig. 2: Verifying container status

3. Node.js and MongoDB Tutorial

To set up the application, we will need to navigate to a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

3.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the required dependencies.

package.json

{
  "name": "mongodb",
  "version": "1.0.0",
  "description": "nodejs and mongodb tutorial",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "monogodb",
    "docker",
    "restapi",
    "express"
  ],
  "author": "c-danielatlas",
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^2.0.11"
  },
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongoose": "^5.13.2"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

3.2 Creating the model class

We will define the Employee model in mongoose. Create a new folder called model inside the root folder. Now create a file called employee.js with the following content. This model will represent a collection in the mongo database.
employee.js

const mongoose = require('mongoose');

const EmployeeSchema = mongoose.Schema({
    first_name: {
        type: String
    },
    last_name: {
        type: String
    },
    email_address: {
        type: String,
        required: [true, 'Email address is required']
    },
    phone_number: {
        type: String
    },
    date_of_joining: {
        type: Date,
        default: Date.now
    }
});

module.exports = mongoose.model('Employees', EmployeeSchema);

3.3 Creating the routes file

Create a new folder called routes inside the root folder. Now create a file called employee.js with the following content. The file will be responsible to handle the incoming HTTP requests from the client and perform the CRUD operations with the help of the mongoose model.

employee.js

const express = require('express');
const router = express.Router();
const Employee = require('../models/employee');

// submit employee details
router.post('/', (req, res) => {
    // todo - skipping request body validation for brevity

    // creating employee obj
    var employee = new Employee({
        first_name: req.body.first_name,
        last_name: req.body.last_name,
        email_address: req.body.email_address,
        phone_number: req.body.phone_number
    });

    employee.save()
        .then((response) => {
            res.status(201).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// get back all employees
router.get('/', (req, res) => {
    Employee.find()
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// get back a single employee
router.get('/:id', (req, res) => {
    console.log('Searching id = %s', req.params.id);
    Employee.findById(req.params.id)
        .then(response => {
            if (!response) {
                res.status(404).json({ 'message': 'Resource not found' });
            } else {
                res.status(200).json({ 'message': response });
            }
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// delete all employees
router.delete('/', (req, res) => {
    Employee.deleteMany()
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// delete an employee
router.delete('/:id', (req, res) => {
    console.log('Deleting id = %s', req.params.id);

    // todo - skipping find-by-id validation for brevity

    Employee.deleteOne({ _id: req.params.id })
        .then(response => {
            res.status(200).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

// update an employee
router.patch('/:id', (req, res) => {
    console.log('Updating id = %s', req.params.id);

    // todo - skipping find-by-id validation for brevity

    Employee.updateOne(
        { _id: req.params.id },
        { $set: { phone_number: req.body.phone_number } })
        .then(response => {
            res.status(204).json({ 'message': response });
        }).catch(err => {
            res.status(500).json({ 'message': err });
        });
});

module.exports = router;

3.4 Setting up Express webserver

In the root folder add the following content to the index.js file.

index.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

// parsing request of content-type as application/json
app.use(bodyParser.json());

// import routes
const employeeRoutes = require('./routes/employees');
app.use('/employees', employeeRoutes);

// connect to db
const DB_CONNECTION = 'mongodb://localhost:27017/employeedb';
mongoose.connect(DB_CONNECTION, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => {
        console.log('connected to db');
    }).catch(err => {
        console.log('error while connecting to db', err);
    });

// start app
const PORT = process.env.port || 3000;
app.listen(PORT, () => {
    console.log(`Server started on port ${PORT}`);
});

4. Run the Application

To run the application navigate to the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on port number 3000.

node js mongo db tutorial - starting the app
Fig. 3: Starting the application

5. Demo

You are free to use postman or any other tool of your choice to make the HTTP request to the application endpoints.

// submit employee details
// HTTP post
// Sample request body -
// {
//     "first_name": "John",
//     "last_name": "Doe",
//     "email_address": "john.doe@example.com",
//     "phone_number": "1234567890"
// }
http://localhost:3000/employees/

// get all employees
// HTTP get
http://localhost:3000/employees/

// get a single employee
// HTTP get
http://localhost:3000/employees/60e9b70dbe4c540fa4c3bb21

// update a single employee
// HTTP patch
http://localhost:3000/employees/60e9bea87f9c4640f0b27617

// delete a single employee
// HTTP delete
http://localhost:3000/employees/60e9bea87f9c4640f0b27617

// delete all employees
// HTTP delete
http://localhost:3000/employees/

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

6. Summary

In this tutorial, we learned how to create a MongoDB on Docker and create simple Node.js RESTful APIs with an Express web server application to perform the CRUD operations. You can download the source code and the postman collection from the Downloads section.

7. Download the Project

This was a tutorial to create a CRUD application in Node.js with MongoDB.

Download
You can download the full source code of this example here: Node.js and MongoDB Tutorial

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button