Subscribe via RSS Feed

Developing Web Application with Node.js, Express.js and MongoDB (MongoJS module)

May 17, 2013 7 Comments


This is our second proof of concept towards make a web application with Javascript based Web Server.

To make this possible, we have selected -

1> Node.js for server side development

2> Rest based web service creation with express.js

3> Database – MongoDb

4> Node.js MongoDb Module Extention (mongojs)

We have created a Proof of Concept with Javascript based web server, where we have focused on dealing with NoSql (MongoDB) with javascript based framework Node.js.

Our initial code can be downloaded here.

Architecture at a glance -

Node-Express-Mongo

So here are the steps -

Installation -

A> Download and install Node.js from here.

B> To Develop the application we need to install mongojs module for Node.js

Command – npm install mongojs (should be connected to internet)

C> We need to install express.js for node.js

Command – npm install express  (should be connected to internet)

Configuration Code -

Now, we will try to describe the code portion -

 
var application_root = __dirname,
    express = require("express"),
    path = require("path");

Here we have initialised the express.js within javascript variables in respect of Node.js concept.

 
var app = express();

Here we have initialised the express web server in app variable.

 

var databaseUrl = "sampledb"; 
var collections = ["things"]
var db = require("mongojs").connect(databaseUrl, collections);

Here we have made the connection to the mongodb database using the Node.js mongojs module extension library.

 
// Config

app.configure(function () {
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(application_root, "public")));
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

Here we have made the configuration related to express.js

Rest Services Code -

 
app.get('/api', function (req, res) {
  res.send('Our Sample API is up...');
});

Here we have made our first REST based web service and tested whether the express.js is up.

Our sample api will be  - http://127.0.0.1:1212/api (Get Method)

 
app.get('/getallusers', function (req, res) {
	db.things.find('', function(err, users) {
	if( err || !users) console.log("No users found");
	  else 
	{
		res.writeHead(200, {'Content-Type': 'text/plain'});
		str='';
		users.forEach( function(user) {
			str = str + user.username +'\n';
		});
		res.end( str);
	}
  });
});

Here we have created another REST api to get all username from user collection and so have done the mongojs query.

Our sample api will be  - http://127.0.0.1:1212/getallusers (Get Method)

 
app.get('/user/:username', function (req, res){
	res.writeHead(200, {'Content-Type': 'text/plain'});
	//res.end( req.params.username);
	user = req.params.username;
	db.things.find({username:user}, function(err, users) {
		 str='';
		 if( err || !users) console.log("No users found");
		 else 
		{
			users.forEach( function(user) {
				str = str + 'User is '+ user.username +'\n';
				str = str + 'and email is '+ user.email +'\n';
				res.end( str);
			});
		 }
      }); 
});

Here we have selected particular user by his/her username in database via REST calling.

Our sample api will be  - http://127.0.0.1:1212/user/firstuser (Get Method)

 
app.post('/insertmongouser', function (req, res){
  console.log("POST: ");
  res.writeHead(200, {'Content-Type': 'text/plain'});
  user = req.body.username;
  passwd = req.body.password;
  emailid = req.body.email;

  db.things.save({email: emailid, password: passwd, username: user}, function(err, saved) {
  if( err || !saved ) res.end( "User not saved"); 
  else res.end( "User saved");
});
});

Here we have made a POST request to create an user via REST calling.

Our sample api will be  - http://127.0.0.1:1212/insertmongouser (Post Method)

 
// Launch server
app.listen(1212);

We have made the server to listen at 1212 port. Also below is the samplemongodb.html file which is used to call the REST Post API to insert the user.

 

<html>
<body>
<form name="input" action="http://127.0.0.1:1212/insertmongouser" method="post">
Username: <input type="text" name="username">
Password: <input type="text" name="password">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>

Now run node appmongodb.js from command shell.

Enter your email address:

Delivered by FeedBurner

javascriptnosqlbook