Create Operator in Express.JS Rest API and Mongoose


Create a database with the name is learnexpressjsrestapi. This database have 1 collection: Product collection

/* Create learnexpressjsrestapi database */
use learnexpressjsrestapi

/* Create Product collection */
db.createCollection('product');

/* Dumping data for `product` collection */
/* 1 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45023"),
    "name" : "Mobile 1",
    "price" : 45.0,
    "quantity" : 4.0,
    "status" : true
}

/* 2 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45024"),
    "name" : "Mobile 2",
    "price" : 12.0,
    "quantity" : 7.0,
    "status" : true
}

/* 3 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45025"),
    "name" : "Mobile 3",
    "price" : 28.0,
    "quantity" : 8.0,
    "status" : true
}

/* 4 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45026"),
    "name" : "Laptop 1",
    "price" : 39.0,
    "quantity" : 12.0,
    "status" : false
}

/* 5 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45027"),
    "name" : "Laptop 2",
    "price" : 86.0,
    "quantity" : 23.0,
    "status" : true
}

/* 6 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45028"),
    "name" : "Tivi 1",
    "price" : 22.0,
    "quantity" : 7.0,
    "status" : true
}

/* 7 */
{
    "_id" : ObjectId("5a77af0153b19a9778e45029"),
    "name" : "Tivi 2",
    "price" : 86.0,
    "quantity" : 23.0,
    "status" : false
}

Create LearnExpressJSRestAPIWithRealApps folder and select to this folder in Visual Studio Code

Use the following command to install Mongoose:

npm install mongoose --save




Use the following command to install Express.JS:

npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save

Create schemas folder in Node project. Create product.schema.js file into schemas folder. Declare schema for product collection as below:

var mongoose = require('mongoose');

var ProductSchema   = new mongoose.Schema(
    {
      name: String,
      price: Number,
      quantity: Number,
      status: Boolean
    },
    {
        versionKey: false
    }
);

module.exports = mongoose.model('Product', ProductSchema, 'product');

Create a new folder named api inside the server project. Create product.api.js file inside api folder contains Rest APIs insert new data from client

var mongoose = require('mongoose');
var Product = require('../schemas/product.schema');

var ProductAPI = {
    create: function (request, response) {
        var newProduct = new Product({
            name: request.body.name,
            price: request.body.price,
            quantity: request.body.quantity,
            status: request.body.status
        });

        newProduct.save(function (error) {
            if (error) {
                throw error;
            }
            else {
                response.status(200).json(newProduct);
            }
        });
    }
};

module.exports = ProductAPI;




Inside the api folder create a new file named index.js. This file will hold all the routes needed for rest api in server.

var express = require('express');
var mongoose = require('mongoose');

var router = express.Router();

mongoose.connect('mongodb://localhost:27017/learnexpressjsrestapi');

var ProductAPI = require('./product.api');

router.post('/product/create', ProductAPI.create);

module.exports = router;

At the root of server project, create a file named server.js. This will be the entry point into node application. This will start the server and listen on a local port

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.use('/api', require('./api/index'));

var server = app.listen(9090, function () {
	var host = server.address().address;
	var port = server.address().port;
	console.log("Server listening at http://%s:%s", host, port)
 });

Create LearnExpressJSRestAPIWithRealApps_Client folder and select to this folder in Visual Studio Code

Use the following command to install http module

npm install http --save

Create a new folder named api inside the client folder. Create product.api.js file inside api folder contains method call Rest API from server

var http = require('http');

var ProductAPIClient = {
    create: function (product, callback) {
        var options = {
            hostname: 'localhost',
            port: 9090,
            path: '/api/product/create',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        };

        var post_request = http.request(options, function (response) {
            var str = '';
            response.on('data', function (chunk) {
                str += chunk;
            });
            response.on('end', function () {
                callback({
                    status: response.statusCode,
                    body: str
                });
            });
            response.on('error', function (error) {
                callback({
                    status: response.statusCode,
                    error: error.message
                });
            });
        });

        post_request.write(JSON.stringify(product));
        post_request.end();
    }
};

module.exports = ProductAPIClient;




At the root of client project, create a file named client.js. This will call Rest API and display results

var ProductAPIClient = require('./api/product.api');

var product = {
    name: 'Tivi 3',
    price: 20,
    quantity: 14,
    status: true
};

ProductAPIClient.create(product, function (result) {
    if (result.error) {
        console.log(result.error)
    } else {
        var product = JSON.parse(result.body);
        console.log('Status: ' + result.status);
        console.log('New Product Info');
        console.log('Id: ' + product._id);
        console.log('Name: ' + product.name);
        console.log('Price: ' + product.price);
        console.log('Quantity: ' + product.quantity);
        console.log('Status: ' + product.status);
    }
});
Status: 200

New Product Info
Id: 5a77c0408be4461274c14e15
Name: Tivi 3
Price: 20
Quantity: 14
Status: true