Tuesday, September 23, 2014

NodeJs mongoDB : With sample application

Hi,

NodeJs connectivity with the MongoDB Database.
Here, i am assuming that you have NodeJS, NPM and socket.io installed on your machine. If not kindly follow the below URL to install the above tools:
http://tarunlinux.blogspot.in/2014/09/nodejs-basics.html

Lets start to create sample appication on NodeJs with mongoDB connectivity.

Step 1: Install mongoDB on your machine... Please follow the below link to setup mongoDB..
http://tarunlinux.blogspot.in/2014/09/mongodb-basics.html

Step 2: Install NodeJS mongoDB dependency with the below command:

1
# sudo npm install mongodb



It will install mongodb module in your application.

Step 3: Create server.js file for the nodejs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
var mongo = require('mongodb').MongoClient;
var client = require('socket.io').listen(8080).sockets;  //Load socket.io module

mongo.connect('mongodb://localhost/tarundb', function(err, db){
    client.on('connection', function(socket){
        var col = db.collection('employee'); //connect with collection of tarundb

        //Insert data into mongodb
        col.insert({name: 'Tarun', age:26}, function() {
            console.log("Inserted");
        });
        
        //emit all the records
        col.find().limit(100).toArray(function(err, res){
            if(err) throw err;
            
            socket.emit('all-data', res);
        });
    });
});


Step 4: Create Index.html file for the frontend:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
    <head>
        <title> NodeJs MongoDB APP </title>
    </head>
    <body>
        <div class="data-set"></div>
        <script src="http://localhost:8080/socket.io/socket.io.js" type="text/javascript"></script>
        <script src="http://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
        <script>
        (function(){
            try{
                var socket = io.connect('http://localhost:8080');
            } catch(e){
                console.log(e);
            }
            
            if(socket !== undefined) {
                socket.on('all-data', function(data){
                    for(var i=0; i < data.length; i++) {
                        $(".data-set").append('<li>'+ data[i].name +'</li>');
                    }
                });
            }
        })();
        </script>
    </body>
</html>


Step 5: Now you have to run server.js file
# nodejs server.js

Then open your browser, with url: http://localhost:8080/
Where you will see the mongoDB connectivity and their data.

I hope it will help you for NodeJs Connectivity with MongoDB.. If you have any query, please put your comments, i highly appreciate that ...

Bye..

No comments :