Tuesday, April 14, 2015

Sample code for Nodejs + Mongodb REST service

Hi,

In a recent assignment, I was supposed to create a PoC of how Nodejs would work with Mongodb to offer RESTful web services. I was very new to Javascript programming as well as Nodejs platform. Then I started reading about Nodejs and went through couple of tutorials and a ebook to understand what it stands for.

Here are few things I noticed and remember after completing my PoC.

1.)    It’s built using Chrome’s Javascript runtime

2.)    It’s lightweight and efficient because of it’s event driven and non-blocking I/O architecture

3.)    Best for data intensive realtime applications like web services, analytics, dashboard service etc.

Benefits and possible usage:

1.)    Great Performance – it’s all javascript running with chrome’s javascript engine.

2.)    Fast development – You don’t need a lot of software setup the way you need for Java or Microsoft projects.

3.)    Huge flexibility to do both high level and low level functionality.

4.)    It is natural choice for developing a backend system which needs to be scaled faster and still maintain it’s performance.

5.)    Good choice to create various collaborative components like chat room or message boards.

6.)    You can achieve both scalability and performance on commodity servers. You don’t need high end servers in order to achieve these features for your apps.

7.)    A good choice for developing web services with Mongodb, because both of them understand JSON like their first language.

8.)    For any web portal using extensive Javascript (be it Angular or ExtJS or any other form), Nodejs can be very natural and obvious choice since using Javascript on both sides would give you better performance & flexibility.

9.)    Nodejs community publishes various kinds of packages (like express and others), which can be plugged into your development and reused like never before. Since it’s plain javascript, more and more packages are coming out faster & often. This, in turn supports faster development as well as it support community development.

10.) More and more Mobile apps and sites are being developed using various Javascript libraries like JQuery and AngularJS instead of Notive code. Hence, Nodejs becomes obvious choice for all such mobile app projects for their backend services.

11.) In a recent trend, Nodejs is increasingly being used to create backend components to analyze log files, convert images/videos and sending out communications like emails and SMSs (also push notifications).

Then the code that I first developed for my PoC. A RESTful service with Nodejs and Mongodb.

This Nodejs web service is deployed on IBM Bluemix PaaS (Platform as a Service).

//following content go into app.js file

// This application uses express as it's web server
// for more info, see: http://expressjs.com
var express = require('express');
var http = require('http');
//var express = require('express');
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
var connectionString = 'mongodb://<username>:<password>@<mongodb-host-name>:<mongodb-port>/dbname';

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

app.get('/test', function (req, res) {
  res.send('Hello World');
});

app.get('/users/:username', function (req, res) {
  MongoClient.connect(connectionString, function (err, db) {
  if (err) throw err;
  if (!err) {
    console.log("Connected to database");
    var collection = db.collection('users');
    var uname = req.params.username;

    //retrive user
    collection.find({"username": uname}).toArray(function (err, result) {
      if (err) {
        console.log(err);
        res.send(err);
      } else if (result.length) {
        console.log('Found:', result);
        res.send(result);
      } else {
        console.log('No document(s) found with defined "find" criteria!');
        res.send('No document(s) found with defined "find" criteria!');
      }
      //Close connection
      db.close();
    });
  }
})
});

//This one updates password or creates new username in DB
app.post('/users/:username/:password', function (req, res) {
  MongoClient.connect(connectionString, function (err, db) {
  if (err) throw err;
  if (!err) {
    console.log("Connected to database");
    var collection = db.collection('users');
    var uname = req.params.username;
    var pwd = req.params.password;
   
    //create JSON for insert
    var user = {"username": uname, "password": pwd};
   
    //First try to update
    collection.update({"username": uname}, {$set: {"password": pwd}}, function (err, numUpdated) {
      if (err) {
        console.log(err);
        res.send(err);
      } else if (numUpdated) {
        console.log('Updated Successfully %d document(s).', numUpdated);
        res.send('Updated Successfully - ' + numUpdated.nModified + ' document(s).');
      } else {
        console.log('No document found with defined "find" criteria!');
            // Insert one user because its not found
            collection.insertOne(user, function (err, result) {
              if (err) {
                console.log(err);
                res.send(err);
              } else {
                console.log('Inserted document! Thanks!');
                res.send('Inserted document! Thanks!' + result);
              }
            }
            );
      }
      //Close connection
      console.log('Now we are closing the db connection...');
      db.close();
    }
    );
  }
})
});

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, appEnv.bind, function() {

    // print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});

No comments:

Post a Comment