CouchDB and CouchApp. Part 1

To write a web application today there are many languages, frameworks and libraries. One of the main languages in this set is JavaScript, because this technique works in most browsers without any additional third-party libraries and quite flexible. At the moment, it is possible to write entire applications to be impressive in its simplicity and efficiency by only using JavaScript. In this series of articles, I want to tell about the two interesting technologies – CouchDB and CouchApp. This two things can help write web applications by using only JavaScript (Of course you need also know HTML/CSS).

Hello CouchDB

So what is CouchDB? CouchDB – is an open source document-oriented database written mostly in the Erlang programming language. Yep, its NoSQL. Main features:
  • Document Storage – All documents stores in JSON format, so schema of records is flexible, like in MongoDB
  • Document Revisions – All documents have list of revisions (old versions of this document), this can help do rollback of documents
  • REST API – it stored all items as a resources, each have unique URI and you can do CRUD (Create, Read, Update, Delete) operations on all resources.
  • Distributed Architecture with Replication – CouchDB was designed with bi-direction replication (or synchronization) and off-line operation in mind. That means multiple replicas can have their own copies of the same data, modify it, and then sync those changes at a later time. The biggest gotcha typically associated with this level of flexibility is conflicts.
  • Eventual Consistency – CouchDB guarantees eventual consistency to be able to provide both availability and partition tolerance.
I also write the legend about CouchDB, which you need to know when reading this articles:
  • Design documents – are a special type of CouchDB document that contains application code.
  • Views – the combination of a map and a reduce function (MapReduce!). For information, map functions are called once with each document as the argument. The function can choose to skip the document altogether or emit one or more view rows as key/value pairs. Map functions may not depend on any information outside of the document. This independence is what allows CouchDB views to be generated incrementally and in parallel. Views used for filtering and finding the documents in CouchDB (No SQL, only Views).
  • Show functions, as they are called, build HTML or another output format by document and have a constrained API designed to ensure cacheability and side effect–free operation.
  • List functions, just as show functions convert documents to arbitrary output formats, allow you to render the output of view queries in any format. The powerful iterator API allows for flexibility to filter and aggregate rows on the fly, as well as output raw transformations for an easy way to make Atom feeds, HTML, CSV files, or even just modified JSON.
First of all you need install CouchDB. Its not covered in this article, because this information simple find in Internet. After installation, check if all work fine by curl request (localhost change by ip of your server, where you install CouchDB):You should see looks like the same string, when all work fine.After building and running CouchDB at http://localhost:5984/_utils/ will be available to web-based interface for managing a database – the Futon.FutonMore screenshots here http://couchdb.apache.org/screenshots.html.By this web interface, you can manage databases and configuration of CouchDB. As you can see, you can manage all data in your database in two ways in CouchDB: by HTTP requests (REST) or from Futon.Now lets talk about documents in CouchDB. In CouchDB exists two main kinds of document. First used for storing information, but design type of document used for storing applications code, which can contain views, shows and list functions, attachments, etc. So, you can build and save design document in CouchDB, which will contain your application and will be working from CouchDB (Futon will serve your application as HTTP server) and using CouchDB as data storage. For creating such type of documents we using CouchApp.

CouchApp – feel power of JavaScript in CouchDB

CouchApp – is a JavaScript and HTML5 applications served directly from CouchDB. Your application on JS/HTML/CSS build and push into CouchDB by this tool. Because it runs inside a database, the application API is highly structured. Exists CouchApp, which written on Python (http://couchapp.org/) and written on Node.js (https://github.com/mikeal/node.couchapp.js). I prefer use Node.js version, because the structure of such application more easy for beginning than Python version.Lets write a simple application, which just say for us information about how many documents in the database. I am using JQuery and JQuery.Couch (https://github.com/daleharvey/jquery.couch.js) when working with javascript. First of all, lets generate application skeleton (Node.js and CouchApp should be installed):The main file here is “app.js”, which contain information about build design document (https://gist.github.com/2002829).“ddoc” is a hash, which pushed in CouchDB as design document. It contain views, show and list functions, rewrites (for routes in application), validation function for CouchDB documents and attachments (js/html/css files of application). As you can see “ddoc” have key “_id” with value “_design/app”. This is the unique key of document in CouchDB save. If document don’t set this key, CouchDB auto generates this key for the document. The keys of design documents must begin from string “_design/”, by such way CouchDB understand that this is design document.Now I added in body of “attachments/index.html” textand push this document on CouchDB server. But before you need create database on CouchDb, which will server this design document. You can do this from Futon or by curl command:Now push this document in this database:Now we can look on results by url http://localhost:5984/simple_on_couch/_design/app/index.htmlCouchDBNow lets add view, which will count all documents in this database. Go to “app.js” and add after “ddoc.views = {};” line:Map function contain all documents and create key/value B-tree and reduce function count sum of values of this B-tree. We can optimize reduce function by this:Latest versions of CouchDB have additional functions for reduce, written on Erlang, which do reduce function quicker, then JavaScript functions. In this code we using function “_count”.Now we need get data from this view and show it in HTML. Add this code to “attachments/index.html”:and this code to javascript file in attachments folder:By line “var db = $.couch.db(‘simple_on_couch’);” we set database for jquery.couch, and by “db.view” send a request to CouchDB view. On the success, we set count of documents into html.CouchDBOn this screen we don’t have documents in the database, except design document. Lets create some documents from Futon:CouchDBAnd reload our application:CouchDB CouchDBAs you can see it works. The next time we will manage documents from our application.The source code of this application you can find by this link (https://github.com/railsware/simple_on_couch/tree/v1).That’s all folks!

Next Steps

In Part 2, I’ll show number of tips for using CouchDB.In Part 3, I’ll deploy our CouchApp application to the production environment.

More information: