Over a million developers have joined DZone.

CouchDB from JavaScript

DZone 's Guide to

CouchDB from JavaScript

· Web Dev Zone ·
Free Resource

CouchDB is maybe the only database that talks HTTP. It exposes a REST-like api you can access directly via JavaScript in order to display views or update documents.

I had a similar good experience with Solr, which is basically Lucene done right and over HTTP. So I decided to try out CouchDB for an university-related project, and quickly build an Ajax-based user interface.

Due to the same origin policy, you will probably serve JS and HTML files of your app from the same host as the CouchDB one, or use some kind of reverse proxy to direct the legitimate HTTP requests arrived to your host to CouchDB.

In my case, I decided to build a CouchApp and simply store all the files in CouchDB, along with the documents; CouchDB will then serve both the HTML and .js files and the views containing Json data. It seems that this is as standard practice for CouchApp.

To access CouchDB from a browser, you can use the XMLHttpRequest object directly, or hiding that beyong a simple wrapper. The wrapper won't do a lot of work, but it certainly simplifies the Api.

I use the jQuery plugin you can find at http://localhost:5984/_utils/script/couch.js in your local CouchDB installation. This library extend the $ global object with a $.couch object which is your entry point in calling CouchDB.


CouchApp is a simple python tool that enables you to code your application locally and push the code into a CouchDB instance.

In fact, the JS library we have seen earlier is used by default in CouchApps. I preferred not to rely on magic however, and build my HTML and JavaScript by calling the $.couch Api directly. Thus I modified the index.html file, generated by couchapp, which already loaded the couchdb-jquery JS Api:

<script src=""></script>
Of course this script in turn loads, between other things, which is the real jQuery plugin you would want to use. It also loads jQuery - which is very handy for quickly building Ajax interfaces.

Beware, the Api is not published, and it may change in the future. Refer to your own jquery.couch.js file to solve any doubt in case the information here gets outdated.
$.couch.db() is the factory method you can use to create your "db connection". Of course no connection is established until you make particular method calls that must communicate with the CouchDB instance. This is how to instantiate a db object:
var db = $.couch.db('databaseName');


These are the most important methods you will call on the db object.

db.openDoc(docId, options, ajaxOptions)

  • docId is the key of a document. No much else to say here.
  • options are parameters for couchDb (this argument is a json object.)
  • ajaxOptions is a Json object too, but is used by jQuery instead. For example the key 'success' should point to the callback that will be called upon completion. This key is no more than what will be passed to the $.ajax() call.

Remember that in JavaScript (thankfully) each input/output communication is asynhcronous. The success callback will be called with the document as the only argument. This is completely obvious for the ones of use who are used to Ajax, but not for server-side programmers.

db.saveDoc(doc, options)

  • doc is a Json object, which represents the entire document. CouchDB handles it without any problem, even if it has a nested structure containing other objects or arrays. However make sure it is real Json: for example functions are not part of the Json standard.
  • options is a Json object. The important keys here are success and error, which are callbacks. success will be called with the HTTP response as the only argument, as always.

db.removeDoc(doc, options)

  • here doc is a subset of the document's data, which should at least contain the doc._id and doc._rev.
  • options is the usual object containing callbacks, which will be passed to $.ajax() directly.

db.view(name, options)

  • name is the path of the view on the server: databaseName/viewName.
  • options is the usual object for jQuery, containing at least the 'success' callback. However there are other options which will be attached in the query string: for example group_level influences the grouping of values in the reduce phase of the view.

success will be called with an object which has a key rows. The key rows contains various objects, which are the result of the MapReduce operation that defines the view. Each row has key and value field. If that sounds obscure, console.log() will be helpful.


With $.couch.js, it is very simple to tie-in some jQuery utility to load a view into a table:
        function loadSales()
db.view("marketing/sales", {
success: function(data) {
for (i in data.rows) {
doc = data.rows[i].value;
html = '<tr>' +
'<td>' + doc.client + '</td>' +
'<td>' + doc.amount + '</td>' +
'<td>' + doc.date_day + '/' + doc.date_month + '/' + doc.date_year + '</td>' +
'<td>' + doc.segment + '</td>' +
It is also very simple to add a doc via a form:

$('button#add_sale').click(function(event) {
var form = $('form#sale');
var doc = {
'amount' : parseInt(form.find('#amount').val()),
'client' : form.find('#client').val(),
'date_day' : parseInt(form.find('#date_day').val()),
'date_month' : parseInt(form.find('#date_month').val()),
'date_year' : parseInt(form.find('#date_year').val()),
'segment' : form.find('#segment').val(),
'type' : 'sale'
success : function() {
$(':input', form).not(':button').val('');
return false;
I hope you will enjoy accessing CouchDB from JavaScript. This is the only database built exactly for that.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}