First steps with Node.js and CouchDB

Reading time ~1 minute

Since there is a lot of new fancy stuff around beside Ruby on Rails, I decided to evaluate Node.js together with Couchbase CouchDB. Node is a server-side JavaScript solution to respond to HTTP requests, CouchDB a document-oriented database.

To get them playing along, I chose Express as Framework and nano as CouchDB connector.

Install node.js, then express and nano: npm install -g express npm install connect npm install nano npm install -d

This is a little example based on the Express application template on how to get data from a CouchDB view. Run the server with node app.js:

<pre> /** * Module dependencies. */

var express = require(‘express’); var connect = require(‘connect’); var nano = require(‘nano’)(‘’) , db = nano.use(‘test’); var request = require(‘request’);

var app = module.exports = express.createServer();

// Configuration

app.configure(function(){ app.set(‘views’, __dirname + ‘/views’); app.set(‘view engine’, ‘jade’); app.use(connect.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(__dirname + ‘/public’)); });

app.configure(‘development’, function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); });

app.configure(‘production’, function(){ app.use(express.errorHandler()); });

// Routes

app.get(‘/’, function(req, res) { data = db.view(“hello”, “world”, {“include_docs”:”true”}, function (_,data) { console.log(data.rows); res.render(‘helloworld.jade’, {data: data.rows}); }); });


console.log(“Express server listening on port %d in %s mode”, app.address().port, app.settings.env); </pre></code>

The corresponding jade template could look like this:

<pre> - for (var k in data) each val, key in data[k] p #{key}: #{val} - if(key == 'value') each val2, key2 in val p #{key2}: #{val2} </pre>

It was a bit tricky to get the code for the params together, but with include_docs=true you can build fancy database joins and complex applications. For more examples on Nano see this article. Enjoy.

Europe on Two Wheels

![Iron 883](/images/2015/07/IMG_7368.jpg)## Barcelona (Spain) - Le Dramont, Cote d'Azur (France)> 648km![Le Dramont](/images/2015/07/IMG_...… Continue reading


Published on September 10, 2014

HTML5 vs. Native [thoughts]

Published on February 26, 2014