Update 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 update data from client

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

var ProductAPI = {
    update: function (request, response) {

        Product.findByIdAndUpdate(
            request.body._id,
            {
                name: request.body.name,
                price: request.body.price,
                quantity: request.body.quantity,
                status: request.body.status
            },
            function (error, result) {
                if (error) {
                    throw error;
                } else {
                    response.status(200).json(result);
                }
            }
        );
    }
};

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.put('/product/update', ProductAPI.update);

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 = {
    update: function (product, callback) {
        var options = {
            hostname: 'localhost',
            port: 9090,
            path: '/api/product/update',
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            }
        };

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

        put_request.write(JSON.stringify(product));
        put_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 = {
    _id: '5a77af0153b19a9778e45026',
    name: 'ABC',
    price: 777,
    quantity: 999,
    status: true
};

ProductAPIClient.update(product, function (result) {
    if (result.error) {
        console.log(result.error)
    } else {
        console.log('Status: ' + result.status);
    }
});
Status: 200