Find Documents with Conditions in MongoDB with 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 provides application/json data for the client

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

var ProductAPI = {
    search: function (request, response) {
        Product.find({$and: [{price: {$gte: request.params.min}}, {$lte: request.params.max}]}, function (error, products) {
            if (error) {
                throw error;
            } else {
                response.status(200).json(products);
            }
        });
    }
};

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.get('/product/search/:min/:max', ProductAPI.search);

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 app = express();

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)
 });

At the root of server project run command: node server.js

Access Rest API use the following url: http://localhost:9090/api/product/find/search/20/40

Output

[
    {"_id":"5a77af0153b19a9778e45025","name":"Mobile 3","price":28,"quantity":8,"status":true},
    {"_id":"5a77af0153b19a9778e45026","name":"Laptop 1","price":39,"quantity":12,"status":false}
    {"_id":"5a77af0153b19a9778e45028","name":"Tivi 1","price":22,"quantity":7,"status":true}
]

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 BASE_URL = 'http://localhost:9090/api/';

var ProductAPIClient = {
    search: function (min, max, callback) {
        return http.get(BASE_URL + 'product/search/' + min + '/' + max, function (response) {
            var str = '';
            response.on('data', function (chunk) {
                str += chunk;
            });
            response.on('end', function () {
                callback({
                    status: response.statusCode,
                    body: JSON.parse(str)
                });
            });
            response.on('error', function (error) {
                callback({
                    status: response.statusCode,
                    error: error.message
                });
            });
        }).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');

ProductAPIClient.search(20, 40, function (result) {
    if (result.error) {
        console.log(result.error)
    } else {
        console.log('Status: ' + result.status);
        console.log('Products List');
        for (var i = 0; i < result.body.length; i++) {
            console.log('Id: ' + result.body[i]._id);
            console.log('Name: ' + result.body[i].name);
            console.log('Price: ' + result.body[i].price);
            console.log('Quantity: ' + result.body[i].quantity);
            console.log('Status: ' + result.body[i].status);
            console.log('===========================');
        }
    }
});
Status: 200

Id: 5a77af0153b19a9778e45025
Name: Mobile 3
Price: 28
Quantity: 8
Status: true
===========================
Id: 5a77af0153b19a9778e45026
Name: Laptop 1
Price: 39
Quantity: 12
Status: false
===========================
Id: 5a77af0153b19a9778e45028
Name: Tivi 1
Price: 22
Quantity: 7
Status: true
===========================