Categories
couchdb nodejs

Working with NodeJS, CouchDB and Express Framework

This is a simple example of using node.js, nano (couch db modules) and the express framework to retrieve some data from a couch instance.

Setting up the modules

We will be using a couch instance from www.iriscouch.com. The database will be named “employees”.

var nano = require('nano')('http://lugomatic.iriscouch.com');
var db = nano.use('employees');

We need to include the express module and create an express server:

var app = require('express').createServer();

With all modules setup it should look like this.

var nano = require('nano')('http://lugomatic.iriscouch.com');
var db = nano.use('employees');
var app = require('express').createServer();

We need to give express access to the imgs, css and js directories so it can retrieve our assets.

app.configure(function(){
 app.use("/public", express.static(__dirname + '/public'));
});

Setting up a route

We are setting up a route to “all” that will call a view from the couch instance and retrieve some data.

Bernie Sanders, a reliable voice on the Left for many issues, is very loud online ordering viagra in his protests about the role of speculators in the high price of gasoline at the moment. Homeopathic medicines are rather safe and effective and cialis in the uk are suggested by industry experts. The body’s excretion mechanisms (involved in the detoxification process) can fight buy line viagra against these harmful agents for a while. Not being able to achieve or sustain an erection was just a fact viagra tabs of life.

app.get('/all', function(req, res){
	db.view('getAll','getAll',function (error, body, headers) {
     res.send(body, 200);
    });
}); 

Starting sever

app.listen(3000);
console.log('App is running at http://localhost:3000');

Point your browser to http://localhost:3000/all. You should see a JSON object return like below. I only added 2 employees for the demo.

{
    "total_rows": 2,
    "offset": 0,
    "rows": [{
        "id": "8c370768eafc4d67b0d743ffc5000e5d",
        "key": "Eric Vaughan",
        "value": ["Web Developer", true]
    }, {
        "id": "8c370768eafc4d67b0d743ffc5002f27",
        "key": "Joe Lopez",
        "value": ["Web Developer", true]
    }]
}

I will go over how to create a couch instance, create a view and add some data in another post.