Friday, April 19, 2013

Connecting to mongoDB from node.js

Current trend in creating websites is use JavaScript for both back end and front end. If you choose to make your website in this way, you will probably need to host your website in a node.js server. If you decide to use mongoDB as your database, which is also a very fast growing technology, you will definitely need a REST API to connect to the database from your node.js server.
I assume by now you have installed node.js and mongoDB to your localhost to develop your web app.
So first open a command prompt and go to a folder you would like install some node.js modules(most probably to a folder you are creating your application.)

now type

npm install express
and then
npm install mongodb
to install express and mongodb driver for node.js (type 1st and let it download the files and then the 2nd). This downloads some files to a folder named node_modules.

Then create a server.js file in your root directory and paste the code bellow.


var express = require('express'),
    apis = require('./routes/apis');

var app = express();

app.configure(function () {
    app.use(express.logger('dev'));     /* 'default', 'short', 'tiny', 'dev' */
    app.use(express.bodyParser());
});

app.get('/:table', apis.findAll);
app.get('/:table/:id', apis.findById);
app.post('/:table', apis.addEntry);
app.put('/:table/:id', apis.updateEntry);
app.delete('/:table/:id', apis.deleteEntry);

app.listen(3000);
console.log('Listening on port 3000...');


This will create a web server listening on the port 3000.

Now create a folder named routes and create apis.js file in the folder and add the code bellow.


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('cvstore', server);

db.open(function(err, db) {
    if(!err) {
        console.log("Connected to database");
    }
});

exports.findById = function(req, res) {
    console.log("asked3");
    var id = req.params.id;
    var table = req.params.table;
    console.log('Retrieving wine: ' + id);
    db.collection(table, function(err, collection) {
        collection.findOne({'_id': new BSON.ObjectID(id)}, function(err, item) {
            res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Content-Type', 'application/json');
            console.log(item);
            res.send(item);

        });
    });
};

exports.findAll = function(req, res) {
    var table = req.params.table;
    console.log("asked");
    db.collection(table, function(err, collection) {
        console.log("asked1");
        collection.find().toArray(function(err, items) {
            res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Content-Type', 'application/json');
            res.send(items);
        });
    });
};

exports.addEntry = function(req, res) {
    var table = req.params.table;
    console.log(table);
    var wine = req.body;
    console.log('Adding wine: ' + JSON.stringify(wine));
    db.collection(table, function(err, collection) {
        collection.insert(wine, {safe: true}, function(err, result) {
            if (err) {
                console.log("error insert");
                res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Content-Type', 'application/json');
                res.send({'result': 'error'});
            } else {
                var id = JSON.stringify(result[0]._id);
                res.header('Access-Control-Allow-Headers', 'Origin, application/json, Content-Type, Accept');
                res.header('Access-Control-Allow-Origin', '*');
                res.header('Content-Type', 'application/json');
                console.log('Success: ' + JSON.stringify(result[0]));
                res.send({'result': 'success', 'id': id});
            }
        });
    });
}

Now go to the root folder where you saved the server.js file from command prompt and type
node server.js
this run the web server.
Now you can go to your web browser and type localhost:27017/tablename
Replace the tablename with what ever the collection name in the database. You will be able to see all the documents in that collection in the JSON format.
I haven't included the code for updateEntry and deleteEntry here. They will be like the other methods.
If you want to access the database from the application all you have to do is make a ajax call from the application.


$.ajax({
        url: 'http://localhost:3000/' + table,
        type: 'GET',
        'content-Type': "application/json",
        async: false,
        success: function(data) {
        },
        error: function(err) {
        }
    });

Replace 'table' with collection name you want to get the documents. By calling this function you will get a JSON object from the server we created. By making 'POST' request you can add JSON objects to the database.


If you are using a remote database you probably have a username and a password. In that case you will have to change the apis.js file a bit. Replace the relevant lines with this. In the mongolab database server you will have to use a url like 'ds035557.mongolab.com'. First part of the url will change according to your database. 'user' and 'pwd' are user name and password of the database respectively


var server = new Server('ds035557.mongolab.com', 35557, {auto_reconnect: true});
db = new Db('cvsubmit', server);

db.open(function(err, client) {
    if (!err) {
        client.authenticate('user', 'pwd', function(authErr, success) {
            if (authErr) {
                return console.dir(authErr);
            }
            var stream = client.collection('myCollection').find({}).stream();
            stream.on('data', function(item) {
                console.log("Do something with item");
            });
            stream.on('end', function() {
                console.log("Empty!");
            });
        });

    }
});




No comments:

Post a Comment