I’ve had a difficult time finding documentation on the CouchDB jQuery plugin that ships with CouchDB. So, I’ve decided to create my own reference and share it with you. This should cover almost the entire CouchDB API that is available through the version of the plugin that ships with CouchDB 1.1.0.

Setup

The same-origin policy effectively requires that the HTML from which the JavaScript is loaded must be served up from CouchDB (you could instead use a reverse proxy server). This can be done by attaching an HTML document to a CouchDB document. You can do this manually, or through the use of CouchApps.

CouchDB ships with several useful JavaScript libraries, including jQuery. Here is an example of an HTML document that takes advantage of CouchDB’s included JavaScript libraries:

This will result in an AuthSession cookie being set and then sent back to the server on subsequent requests, authenticating the user on each request. The session length is 10 minutes by default, but can be set in CouchDB’s couch_httpd_auth.timeout configuration option.

The second and third parameters are the section and option parameters, respectively. Omit the option parameter if you’d like to retrieve the entire section. Omit both the section and option parameters if you’d like to see the entire server configuration. Add an optional fourth parameter to set the configuration option’s value, which will result in a PUT request with the value.

User DB

JavaScript example:

$.couch.userDb(function(data) {
console.log(data);
});

Resulting HTTP request:

GET http://localhost:5984/_session 200 OK

Console output:

{
"name"="_users",
"uri"="../_users/"
}

The URI will be relative to the HTML executing the script.

New UUID

JavaScript example:

var uuid = $.couch.newUUID();
console.log(uuid);

Resulting HTTP request:

GET http://localhost:5984/_uuids?count=1 200 OK

Console output:

d12ee5ea1df6baa2b06451f44a0156fa

This function takes a count parameter as an optional first parameter. If the count parameter is greater than one, then it will keep a cache of UUIDs that will be returned on subsequent calls, rather than making another request to the server.

Note that the HTTP response includes an Etag HTTP header. If you do a subsequent request for the same document, and your client supports caching and conditional HTTP requests, then an If-None-Match header should be sent using the value from the previous response’s Etag header. If the document has not been modified, then CouchDB will send a 304 Not Modified response and no response body, saving bandwidth and speeding up the response.

This creates a temporary view as defined by your map and reduce functions. Temporary views are useful in development, but should be replaced with views permanently saved to design documents for production. Temporary views are slow, especially with a large number of documents.