How to create a nodejs mongodb rest api and test with postman

Spread the love

Nodejs mongodb rest api

Representational State Transfer or RESTful web services are based on REST architecture. Using RESTful web services, clients can access resources on a server. Previously restful web services in codeigniter, and  SOAP based web services in php were discussed in detail. In this tutorial you are going to learn how to create a nodejs mongodb rest api.

HTTP methods are used to perform different operations in RESTful web services.

  • GET method is used to perform a read operation,
  • PUT method is used to update a resource
  • POST method is used to add new resource
  • DELETE method is used to remove a resource.

You will perform following tasks in this tutorial.

1. Create a MongoDB database and collection to store products.

2. Create NodeJS API to fetch all or single product information.

3. Create NodeJS API to add a product, update an existing product, and delete a product.

4. Test API using Google Chrome’s Postman extension.

MongoDB Installation

MongoDB is a popular No-SQL document database. You can install MongoDB community edition on Windows, Mac, or Linux operating systems. Visit mongodb download page, download and install MongoDB on your system.

Running MongoDB

To run mongoDB visit this article and read the section Running mongoDB for detailed instructions. Open mongodb interactive shell on command line.

Create a MongoDB database

To create onlinestore database, go to the command line and type.

> use onlinestore

The current database will be switched to onlinestore database.

Create products collection and insert records

Run the code below to create a collection of products and insert sample data into it.

db.product.insert([{ "_id" : ObjectId("5899b8369ba2868af6d141d5"), "product_name" : "Apple IPhone 6", "price" : "$630", "category" : "Mobile Phone" } ,

{ "_id" : ObjectId("5899b8369ba2868af6d141d6"), "product_name" : "Sony Vio", "price" : "$1200", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d7"), "product_name" : "Samsung T.V", "price" : "$900", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d8"), "product_name" : "Apple IPAD", "price" : "$400", "category" : "Tablet" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141d9"), "product_name" : "MacBook Pro", "price" : "$800", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141da"), "product_name" : "Dell Laptop", "price" : "$620", "category" : "Laptop" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141db"), "product_name" : "Canon EOS 700D DSLR Camera", "price" : "$400", "category" : "Camera" }, 

... { "_id" : ObjectId("5899b8369ba2868af6d141dc"), "product_name" : "Nikon D7100 DSLR Camera ", "price" : "$440", "category" : "Camera" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141de"), "product_name" : "HTC Phone", "price" : "$200", "category" : "Mobile Phone" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141df"), "product_name" : "LG Monitor", "price" : "$500", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e0"), "product_name" : "Samsung Printer", "price" : "$320", "category" : "Electronics" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e1"), "product_name" : "Samsung Gear Live Black - Made for Android", "price" : "$250", "category" : "Watch" } ,

... { "_id" : ObjectId("5899b8369ba2868af6d141e2"), "product_name" : "Apple Watch", "price" : "$380", "category" : "Watch" } ])


This code creates a collections named products in onlinetore database. To view inserted records type db.products.find().pretty(). You can view the records.

 

Nodejs mongodb rest api

 

NodeJS installation and Project Creation

To install NodeJS, visit NodeJS website, download latest version from Nodejs Download page and install it. After installation create a folder named nodeJs-mongodb-rest-api and type command.

cd nodeJs-mongodb-rest-api

Now type

NPM init

Enter basic information about API such as name, description and entry point of app or you can go with default settings to generate a package.json file.

nodejs mongodb rest api

Following package.json file is generated.

nodejs-mongodb rest api package json

 

Install mongoose module

Mongoose is used to model application data models using a schema. Mongoose has built in features for querying database, validating input etc. Products collection in mongoDB database is mapped by a schema in mongoose.

npm install --save mongoose

Install Express module

To install express module run this command on command.

npm install --save express

Express framework is installed and is used to create a web server.

 Create web server using express

Open the project folder in your favorite IDE, create a file app.js. and add the following code. productModel, mongoose, and the express module is included. A database connection is created using mongoose. Express module is used to create a web server. Web server listens on port 3000.

var express = require('express'),

  app = express(),

  port = process.env.PORT || 3000,

  mongoose = require('mongoose'),

  Product = require('./restapi/models/productModel'),

  bodyParser = require('body-parser');

mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost/onlinestore', { useMongoClient: true });


app.use(bodyParser.urlencoded({ extended: true }));

app.use(bodyParser.json());

var routes = require('./restapi/routes/productRoutes');

routes(app);

app.use(function(req, res) {

  res.status(404).send({url: req.originalUrl + ' not found'})

});

app.listen(port);

console.log('Online Store -  RESTful web services with Nodejs started on: ' + port);

Next create a directory named restapi. In restapi directory create directories named controller, models and routes.

Create Controller, Model and Routes files

In controller directory create a file productController.js, productModel.js in models and productRoutes.js in routes directory.

Create product schema using Mongoose

Open models folder in restapi directory. Add code in file productModel.js.

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var productSchema = new Schema({

  product_name: { type: String, Required:  'Product name cannot be left blank.' },
  
  price:    { type: String,     Required:  'Product price cannot be left blank.'},
  
  category: { type: String ,    Required:  'Product category cannot be left blank'}

});

module.exports = mongoose.model('Products', productSchema);

Schema for product collection is defined. In schema product_name, price and category represent a key in the collection. Each column has a data type, In this schema data type for all columns is  String. But Number, Date, Boolean or ObjectID can also be used.

Finally Products model is exported using module.exports object. In other files this model is included via require method.

Create a controller in nodejs mongodb rest api

Open file prodcutsController.js in the controller directory. Add the following code.

'use strict';

var mongoose = require('mongoose'),

Product = mongoose.model('Products');

exports.products = function(req, res) {

  Product.find({}, function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

exports.add = function(req, res) {

  var new_product = new Product(req.body);

  new_product.save(function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};



exports.update = function(req, res) {

  var id = mongoose.Types.ObjectId(req.query.productId);

  Product.findOneAndUpdate({_id: id}, req.body, {new: true}, function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

exports.delete = function(req, res) {

  var id = mongoose.Types.ObjectId(req.query.productId);

  Product.remove({

    _id: id

  }, function(err, product) {

    if (err)

      res.send(err);

    res.json({ message: 'Product successfully deleted' });

  });

};

First mongoose module is included. Next product model is assigned to product variable.

Fetch all products method

To fetch all products from database, find method is used. You can see empty {}. This is used to apply criteria. If there is no error, a JSON encoded products array is returned to client.

exports.products = function(req, res) {

  Product.find({}, function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

Fetch a product method

A single product information can be fetched using getproduct method. Client sends a productId. ProductId is passed to Product Model’s findById method. JSON encoded product data is returned to client.

exports.getproduct = function(req, res) {

  var productId = req.query.productId;

  Product.findById(mongoose.Types.ObjectId(productId), function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

Add new product method

Adding new product to database is done by using add method. Client sends new product data to web service. Data is passed to save method. On success newly added product data is returned to client.

exports.add = function(req, res) {

  var new_product = new Product(req.body);

  new_product.save(function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

Update method to update existing product

An existing product information is updated using update method. Client sends updated product information with productIdfindOneAndUpdate method is used to update information of an existing product .On success JSON encoded updated product data is sent to client.

exports.update = function(req, res) {

  var id = mongoose.Types.ObjectId(req.query.productId);

  Product.findOneAndUpdate({_id: id}, req.body, {new: true}, function(err, product) {

    if (err)

      res.send(err);

    res.json(product);

  });

};

Delete method in nodejs mongodb rest api

To remove a product from database delete method is defined. Product Id parameter is passed by client and is further passed to remove method of Product schema. On successful deletion a message, otherwise an error is returned to client.

exports.delete = function(req, res) {

  var id = mongoose.Types.ObjectId(req.query.productId);

  Product.remove({

    _id: id

  }, function(err, product) {

    if (err)

      res.send(err);

    res.json({ message: 'Product successfully deleted' });

  });

};

Create Routes for nodejs mongodb REST API

In Routes directory, open a file productRoutes.js.

'use strict';

module.exports = function(app) {

    var product = require('../controllers/productController');

    app.route('/products')

        .get(product.products)

        .post(product.add);

    app.route('/products/:productId')

        .get(product.getproduct)

        .put(product.update)

        .delete(product.delete);

};

First product controller is included, then in app.route products route is created. product.products GET method is used for fetching all products and product.add POST method for adding a product.

product.:productId route is created to fetch, update or delete a product. Client is required to send a productId with request. product.getproduct controller method is used to get a single product information. To update a product information product.update method is defined. Next for deleting a product, delete method of controller is used.

Testing nodejs mongdb REST API

Google Chrome’s Postman extension is used to test nodejs mongodb rest api. To install Postman extension click on Windows menu in Chrome browser. Click on extensions. Click on Get more extensions. In left panel search bar type Postman. In search results you can see Postman, click Add to Chrome.

After installation, open Postman. You can see a dropdown for HTTP methods and an address bar for adding a URL. When user clicks on Send button request is sent to server. Params button is used to add parameters to web service calls, such as productId.

nodejs mongodb rest api

HTTP methods that can be used.

nodejs mongodb rest api - postaman methods

Running nodejs mongodb rest api application

Open command line and go to project folder. Type Command

npm install

Next type command below. This will start the web server.

node app.js

Fetch all products

Open browser and type following URL. You can see the list of all products.

http://localhost:3000/products

nodejs mongodb rest api

 

In Postman add the URL in address bar and click Send button, you can view the list of products. nodejs mongodb rest api - display all products

Fetch a product using getproduct route

In order to fetch a single product information, add the URL in address bar of postman, data for productId: 589a18039341bf7e6dad5f77 is fetched from server.

http://localhost:3000/products/getproduct/?productId=589a18039341bf7e6dad5f77

nodejs mongodb rest api select one product

Add a new product using nodejs mongodb rest api

To add a new product add the http://localhost:3000/products/ into address bar of Postman. Select POST method in HTTP methods drop down. Click on Body. There are multiple options, click on x-www-form-urlencoded. You can enter data as Key, Value pairs. Key contains column name and value contains value for columns in collection.

So in Key add product_name, price and category. For values add Samsung Galaxy 8, $450 and Electronics. Click Send button. You can view the newly added product with _id generated from database. New product data is returned to client. 

nodejs mongodb rest api add product

 

Update a product using nodejs mongodb rest api

To update a product information update method is defined. Suppose you need to change the information of the product with “_id”: “599731e11f3b95278c47b050”. This product is added above using add method.

{
    "product_name": "Samsung Galaxy S8",
    "price": "$450",
    "category": "Electronics",
    "_id": "599731e11f3b95278c47b050"
}

In HTTP methods drop down select PUT.  In address bar type the URL  http://localhost:3000/products/update. Click on params and add Id of product to be updated.

Next click on Body and then x-www-form-urlencoded. In key-value pairs, add updated data. Click on Send button. You can view updated document as a result. The status code 200 is returned.

nodejs mongodb rest api add product

Delete a product using nodejs mongodb rest api

Delete method is used to remove a product from collection. In HTTP methods drop down select DELETE and add URL in address bar.

http://localhost:3000/products/delete/?productId=589a18039341bf7e6dad5f77

Click on Send button. Product is deleted. You can see the success message from server. A status code 200 is returned.

nodejs mongodb rest api delete method

Summary

To summarize, in this tutorial on nodejs mongodb rest api, a mongodb database and collection is created. A nodejs mongdb rest api is created to select, add, update and delete a product. Source code can be cloned or downloaded from this Github repository.

https://github.com/programmer-blog/nodejs-mongodb-restful-api

Please leave your feedback or comments, To stay updated on latest articles, please subscribe to our newsletter or follow us on twitter.

 

Related Articles:

 

Previous Article:

Next Article:

 

Check Also

How to use arrow functions in javascript

Introduction to arrow functions in javascript

Spread the loveLast updated:22nd March, 2021Arrow functions in JavaScript Arrow function were introduced in ES6 …