This Document i would like to create a one page App for CRUD operations on MongoDB using UI5 as Front end. This would be MEAN stack app and instead of Angular Js will use SAP UI5 as front end. So it would be MEUI5N stack

Tools required.

    • Git (for Code Repo)
    • Mongo DB (No SQL DB)
    • Express Js (Framework for Web and Mobile Applications based on Node JS)
    • SAPUI5 (HTML5 based UI)
    • Node js (Application Server– JavaScript based Server side Engine)

There are tons of examples from web for installing the above tools

But would present the main configuration steps for the above  tools after installing with the default settings.

MongoDB : create data/db folder in the installation folder of MongoDB and use mongod in cmd prompt to start the server and mongo  in other cmd window to start mongo DB client


use empdb

In mongoDB  we will create the empdb database using above command in mongo client shell.

So For running this app there should be a empdb database and under it a empdata collection should be created

Since this application runs on the Node js server the UI5 libraries folder need to be downloaded from http://openui5.org/download.html

Extract the UI5 library and copy the resource folder in unzipped folder  to the project folder location.The project structure would be  as below

/wp-content/uploads/2016/08/structure_1009794.jpg

The most important files are server.js and package.json . create a package.json file and Paste the below  code in package.json file



{
"name": "SAP-UI5",
"version": "0.1.1",
"private": true,
"dependencies": {
    "express": "3.x",
    "mongodb": "^2.2.5",
    "node-inspector": "0.7.x"
}
}

Create a file server.js and add the following code



var express = require('express'),
emp = require('./routes/employee');
var app = express();
app.use(express.static(__dirname));
app.configure(function () {
    app.use(express.logger('dev'));    /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
});
app.get('/employees', emp.findAll);
app.post('/employee', emp.addEmp);
app.put('/employee/:id', emp.updateEmp);
app.get('/employee/:id', emp.findById);
app.delete('/employee/:id', emp.deleteEmp);
app.listen(3000);
console.log('Listening on port 3000...');
var mongo = require('mongodb');
var Server = mongo.Server,
    Db = mongo.Db,
    BSON = mongo.BSONPure;
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('empdb', server);
db.open(function(err, db) {
    if(!err) {
        console.log("Connected to 'empdb' database");
        db.collection('empdata', {strict:true}, function(err, collection) {
            if (err) {
                console.log("The 'empdata' collection doesn't exist. Creating it with sample data...");
              populateDB();
            }
        });
    }
});
var populateDB = function() {
  var employees = [
    {
        id: "1",
        name: "John",
        dob: "08/06/1977",
        gender: "Male",
        designation: "Consultant"
    },
      {
        id: "2",
        name: "Robert",
        dob: "09/08/1977",
        gender: "Male",
        designation: "Sr.Consultant"
    }
    ];
  db.collection('empdata', function(err, collection) {
        collection.insert(employees, {safe:true}, function(err, result) {});
    });
};

The above server.js is calling  another js file in routes folder which is employee.js so Create a js file called employee in route folder and add the below code in the js file.


exports.findAll = function(req, res) {
    db.collection('empdata', function(err, collection) {
        collection.find().toArray(function(err, items) {
            res.send(items);
        });
    });
};
exports.addEmp = function(req, res) {
    var emp = req.body;
    console.log('Adding Employee: ' + JSON.stringify(emp));
    db.collection('empdata', function(err, collection) {
        collection.insert(emp, {safe:true}, function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}
exports.deleteEmp = function(req, res) {
var empToDelete = req.params.id;
db.collection('empdata',function(err,collection){
collection.remove({'id':empToDelete},function(err){
  res.send((err === null) ? { msg: '' } : { msg:'error: ' + err });
})
})
}
exports.updateEmp = function(req, res) {
  var id = req.params.id;
    var emp = req.body;
  db.collection('empdata', function(err, collection) {
        collection.update({'id':id},emp,function(err, result) {
            if (err) {
                res.send({'error':'An error has occurred'});
            } else {
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send(result[0]);
            }
        });
    });
}
exports.findById= function (req,res) {
var empId = req.params.id;
db.collection('empdata',function (err,collection) {
    collection.find( { id: empId } ).toArray(function(err, items) {
            res.send(items);
        });
  })
}

The main crux of this Document would be Enabling the REST API for MongoDB  CRUD calls . we can actually perform the REST calls from the same browser.


api.JPG



The functionality in our UI5 app would actually using this REST calls to CRUD our MongoDB database installed locally.


complete project including ui5 app  can be  found on github  link  GitHub – prasadvsrk/meui5n 

node_modules can be created by using npm install command in project folder and resources folder from UI5 SDK site.


just extract the file and copy the web app in your project location .

So from Server side our main things would Node js with node modules folder, Mongo db should be up and running with required db and collection.

Node server.js command  in the same path will start the server.

/wp-content/uploads/2016/08/node_1009916.jpg

Run the app using the URL http://localhost:3000/webapp/index.html


Here are some of the screen shot of app The screen shows the Create and Get operation . clicking on the row in the table will enable the Update and Delete Operation


/wp-content/uploads/2016/08/app_1009887.jpg


/wp-content/uploads/2016/08/app2_1009888.jpg


Thanks

Prasad VSRK


To report this post you need to login first.

4 Comments

You must be Logged on to comment or reply to a post.

  1. Gayathri Vijayakumar

    Hi,

    Its a great blog. I tried to replicate the same example but I’m facing an issues when i start node server.js in command prompt its throws an error. can you please help me.

    (0) 
    1. PRASAD VSRK Post author

      Hi Gayathri,

      Please run npm install command where the package.json file is present.This command installs the dependencies required.

      Thanks

      Prasad

      (0) 

Leave a Reply