AppDividend
Latest Code Tutorials

MongoDB Node js Rest API Example Tutorial

1,025

MongoDB Node js Rest API Example Tutorial is the topic, we will discuss today.  REST APIs handle the server side of the web application. That means that the backend is built once and can provide content or data for the frontend apps like Angular, React or Vue, mobile platforms like Android, iOS or React Native, or other server-side apps. REST stands for Representational State Transfer, and it is the way how the web server should respond to the requests. It allows to read, create, update and delete the data from the database. MongoDB Node js Rest API Example Tutorial is bit long, so stay with me.

Technology Stack

  1. Node.js as a platform
  2. Express as a node.js web framework
  3. MongoDB as a NoSQL Database

Step 1: Installing Node.js on Mac

Go to the terminal and type the following command.

node -v

If you have previously installed Node.js, then it will give you the version that is installed on your mac, if you can’t find then you do need to install it. So let’s assume that you have not installed, so install using the following command. Of course, you can go to nodejs.org and download the mac package, but you can also pull it through homebrew. For that, you have installed homebrew on your machine, and it is straightforward.

Install Node.js and npm with Homebrew

First, install Homebrew.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then run brew update to make sure Homebrew is up to date.

Next, add Homebrew’s location to your $PATH  in your .bash_profile or .zshrc file.

export PATH="/usr/local/bin:$PATH"

Next, install Node.js. It will install npm also with that.

brew install node

Now, test by typing the following command.

node -v
npm -v

Install Node.js on mac

Install MongoDB using homebrew.

Type the following command in your terminal.

brew install mongodb

After downloading Mongo, create the “db” directory. This is where the Mongo data files will live. You can create the directory in the default location by running mkdir -p /data/db

Make sure that the /data/db directory has the right permissions by running the following command.

sudo chown -R `id -un` /data/db

Run the Mongo daemon, in one of your terminal windows run mongod. This should start the Mongo server at port number 27017

mongod

 

Install MongoDB on mac

Run the Mongo shell, with the Mongo daemon running in one terminal, type mongo in another terminal window. This will run the Mongo shell which is an application to access data in MongoDB.

mongo

Start MongoDB on MAC

I have typed the one command to show the default database in the MongoDB, and there are three databases by default.

Step 2: Crafting a new Node.js application.

Okay, now Node.js and MongoDB are correctly installed on our machine. Now, it is time to create a project folder. We will use Yarn package manager to install the dependencies. It is designed by Facebook. First, if you have not installed Yarn previously then install by the following command.

brew install yarn

Test that Yarn is installed by running:

yarn -v

It will give you the version and by checking that we ensure that we have successfully installed yarn on our machine.

MongoDB Node js Rest API Example

Create a project folder and go into that.

mkdir mongorest
cd mongorest

Now, open that folder in your favorite code editor. In my case, it is Visual Studio Code. It is the best code editor for Javascript development in my opinion. Now, install the following packages using yarn.

yarn add express

Express is a web framework that built top on Node.js. It is very lightweight and has all the features that any modern framework has. We will make a simple API that can add the course name and price in the database. The course user can add, edit and update and delete their courses.

Now, install the other dependencies like mongoose, nodemon, and body-parser.

yarn add mongoose body-parser

Install nodemon as a global dependency. We need this because every time we change the file, it restarts the server automatically. So we do not do it manually.

Related Posts
1 of 10
sudo yarn global add nodemon

Create a server.js file inside the root of the project. Define and start the server.

// server.js

const express = require('express');
const app = express();

const PORT = 4000;

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT: ',PORT);
});

Go to the package.json file and add the scripts object.

{
  "scripts": {
    "start": "nodemon server.js"
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.3",
    "mongoose": "^5.0.12",
    "nodemon": "^1.17.3"
  }
}

Now, go to the terminal and type the following command to start the server.

npm start

Start Node js server in mac

Step 3: Connect Node js application to MongoDB.

Create one file inside root called db.js. Export db object from db.js file.

// db.js

module.exports = {
    DB: 'mongodb://localhost:27017/mongorestapi'
}

It is our connection string in which username and password are empty. Our database name is mongorestapi.

Import db.js file inside the server.js file. Remeber you have already run the MongoDB server at port 27017. If you have closed previously then start by typing mongod command.

// server.js

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

const app = express();
const config = require('./db');
const PORT = 4000;

app.use(bodyParser.json());

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

Save the file and switch to the terminal. You can see that our application is connected to the MongoDB database. Note that, we have not created the database in the MongoDB at this time, but still our application is connected. It is right, when we insert any values in the database, then the database itself and its collection will create in the MongoDB. We have also imported body-parser module to parse the data from the form. Use that module as a middleware so every incoming post request can be parsed.

Step 4: Create Model for our application.

Now, we need to create two folders in a root called routes and models.

In models folder, create one model called Course.js. We define the schema for the courses collection. We use Mongoose library for that since it is the best ORM to manipulate the MongoDB database.

// Course.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Define collection and schema for Course
var Course = new Schema({
  course_name: {
    type: String
  },
  course_price: {
    type: Number
  }
},{
    collection: 'courses'
});

module.exports = mongoose.model('Course', Course);

Now, import Course.js file inside server.js.

// server.js

const Course = require('./models/Course');

Step 5: Create routes for our application.

In the routes folder, create one file called CourseRoute.js file.

Now, in that file, we need to import Course.js model as well as express to get Router module.

We will save the values in the database via Mongoose model, so it is required.

// CourseRoute.js

const express = require('express');
const app = express();
const router = express.Router();

const Course = require('../models/Course');

router.route('/add').post(function (req, res) {
    const course = new Course(req.body);
    course.save()
      .then(course => {
      res.status(200).json({'course': 'Course added successfully'});
      })
      .catch(err => {
      res.status(400).send("unable to save the course into database");
      });
  });

module.exports = router;

We have used Router module from express and required the model to save the data in the MongoDB database. Created one route that says that any post request hit  /course/add URL pattern execute that function. It will create an instance of the model and save that data in the database via object-relational mapping.  Now, we need to tell express that hit any request that has resource /course, so this file CourseRoute.js file’s function executed.

So our server.js file looks like this.

// server.js

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

const app = express();
const config = require('./db');
const Course = require('./models/Course');
const CourseRoute = require('./routes/CourseRoute');

const PORT = 4000;

mongoose.connect(config.DB).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database' +err)
});

app.use(bodyParser.json());
app.use('/course', CourseRoute);

app.listen(PORT, function(){
    console.log('Your node js server is running on PORT:',PORT);
});

Here, I have used middleware to redirect any request that has a pattern like ‘/course’ to the CourseRoute.js. So if the request is something like ‘/course/add’ and type is the POST then we can save the data in the database.

// server.js

app.use('/course', CourseRoute);

Now, we can test this in the Postman. So open the Postman. It is the handy tool that can be used to test the API. Remember, you need to POST the data as a raw json format.

Postman API Tutorial

We can see in the response that, we have successfully inserted the values in the database. Now, check in the MongoDB database. Open your mongoshell, if you have not opened then type mongo in the terminal. Now, type the one by one command in your terminal. First, type the following.

show dbs

It will show all of the databases. You can see in the list that our database mongorestapi is created. Now type the following command.

use mongorestapi

So it will switch to the mongorestapi database.

MongoDB Rest API Tutorial

Now, we need to confirm that whether our values are inserted or not. So we need to query the database to show existing collections if any.

show collections

It will tell us, we have courses collection. So switch to courses collection.

use courses

Now, fetch all the documents inside courses collection.

db.courses.find().pretty()

It will give all the collections that have already saved in the database. It dumps all the results in a prettier format.

Fetch all the collections data from the database

If you find empty or nothing, please check your post request in the Postman. You can see my screenshot as well to compare with yours.

Okay, so reading and creating is done. Remaining is Updating and deleting. So, let us do that.

// CourseRoute.js

const express = require('express');
const app = express();
const router = express.Router();

const Course = require('../models/Course');

router.route('/add').post(function (req, res) {
    const course = new Course(req.body);
    course.save()
      .then(course => {
      console.log(course);    
      res.status(200).json({'course': 'Course added successfully'});
      })
      .catch(err => {
      res.status(400).send("unable to save the course into database");
      });
  });

  // Defined get data(index or listing) route
  router.route('/').get(function (req, res) {
    Course.find(function (err, courses){
      if(err){
        console.log(err);
      }
      else {
        res.json(courses);
      }
    });
  });

  //  Defined update route
  router.route('/update/:id').post(function (req, res) {
    Course.findById(req.params.id, function(err, course) {
      if (!course)
        return next(new Error('Could not load Document'));
      else {
        course.course_name = req.body.course_name;
        course.course_price = req.body.course_price;
  
        course.save().then(course => {
            res.json('Successfully Updated');
        })
        .catch(err => {
              res.status(400).send("unable to update the database");
        });
      }
    });
  });
  
  // Defined delete | remove | destroy route
  router.route('/delete/:id').get(function (req, res) {
    Course.findByIdAndRemove({_id: req.params.id}, function(err, course){
          if(err) res.json(err);
          else res.json('Successfully removed');
      });
  });

module.exports = router;

Now, you check yourself and test all the routes in the Postman.

So finally, MongoDB Node js Rest API Example is over. This post is a bit of long, but I have tried my best to show everything from scratch. Hope you enjoy it. If some concepts are remaining then I will cover in upcoming posts. So stay tuned.

Leave A Reply

Your email address will not be published.