Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

Building CouchApps

Create web applications stored in an Apache CouchDB database

Martin Brown (mc@mcslp.com), Professional Writer, Freelance Developer
Martin Brown has been a professional writer for over eight years. He is the author of numerous books and articles across a range of topics. His expertise spans myriad development languages and platforms —Perl, Python, Java™, JavaScript, Basic, Pascal, Modula-2, C, C++, Rebol, Gawk, Shellscript, Windows®, Solaris, Linux®, BeOS, Mac OS/X and more— as well as web programming, systems management and integration. Martin is a regular contributor to ServerWatch.com, LinuxToday.com and IBM developerWorks, and a regular blogger at Computerworld, The Apple Blog and other sites, as well as a Subject Matter Expert (SME) for Microsoft®. He can be contacted through his website at http://www.mcslp.com.

Summary:  Apache CouchDB is an open source document-oriented database management system that allows you to create full database-driven applications using nothing but HTML, CSS and JavaScript. In this tutorial, you will learn how to create your own CouchApp that will perform database operations using Ajax powered by the jQuery framework. The application you will build is a contact manager that allows you to view, create, edit, and delete your contacts.

Date:  03 May 2011
Level:  Intermediate PDF:  A4 and Letter (238 KB | 29 pages)Get Adobe® Reader®

Activity:  47119 views
Comments:  

Displaying a list of contacts

In this section, we will create and display a list of contacts.

Creating a view

To construct a list of contacts, you first need to create a view. This is a JavaScript function that accepts a document as the only argument. The function is executed by Apache CouchDB on every document in the database, and it should output keys (which are used for displaying and filtering information) and corresponding values that you want to output for each document in this view. This process is called the map, as you are mapping the document contents to the information that you want to extract. There is another step, called reduce, which can be used to summarize or simplify the information, but we will not need that for a contacts application.

For example, to output the name from the contact document as the key, and the entire contact record as the value, you would need to write the view shown in Listing 7.


Listing 7. Writing the view

function(doc) {
    if (doc.name) {
emit(doc.name,doc);
    }
}

The anonymous function accepts a single argument, the document. The function then checks to ensure the record has a field called name, and if true, the emit() function then returns two values: The first is the key, and the second is the value, in this case, a copy of the document. Both keys and values can be any valid JSON structure. Keys are used by Apache CouchDB during searching and paging. The values merely contain the information that you want to expose in this view when it is accessed.

Within CouchApp, you can create a new view on the command line using the generate command: $ couchapp generate view contacts byname.

This creates the view byname, in the directory contacts/views/byname, and creates two files, map.js and reduce.js. Edit the map.js file and change it to the function in Listing 6.

You can now push the application to your Apache CouchDB database again. Views are accessible through the browser interface. You can access the view byname on the contacts design document by accessing the URL http://127.0.0.1:5984/contacts/_design/contacts/_view/byname. Again, we are using the design document contact, this time requesting the output of a view (identified by the _view) in the path, with the view name of byname.

At this stage, the view will be empty: {"total_rows":0,"offset":0,"rows":[]}.


Displaying the view within the application

To display the view within our application, we can use the jQuery Couch library to access the view, iterate over each record returned by the view, and then print the record information.

A function for this is shown in Listing 8.


Listing 8. Displaying the view within our application

db = $.couch.db("contacts");
function updatecontacts() {
$("#contacts").empty();

db.view("contacts/byname", {success: function(data) {
    for (i in data.rows) {
        $("#contacts").append('<div id="' + data.rows[i].value._id 
+ '" class="contactrow"><span>' +
                              data.rows[i].value.name +
                              "</span><span>" +
                              data.rows[i].value.phone +
                              "</span><span>" +
                              '<a href="#" id="' + data.rows[i].value._id 
+ '" class="edit">Edit Contact</a>' +
                              "</span><span>" +
                              '<a href="#" id="' + data.rows[i].value._id 
+ '" class="remove">Remove Contact</a>' +
                              "</span></div>"
                             );
    }
}
});
}

The first line in Listing 7 sets a variable used to access the database. The updatecontacts() function first empties the div element that will be used to display the contacts list, then it accesses the results of the view that was just created. If the view access was successful, an anonymous function is called with the returned view data as a JSON structure. The function then iterates over the content, and builds a contact row that outputs the contact name and phone number.

The view results is represented as an array (rows), with each element of the array being a JSON structure containing the contents of the key returned by the view, and the value returned by the view. Hence, we can access the phone number of a contact record returned by the view by accessing the value.field portion of the array element.

The output produces an Edit Contact and a Remove Contact link, which also includes the ID of the underlying Apache CouchDB document. This will be used to provide the information when updating and deleting a contact.

To add this function to the contacts application, create a new file, contacts/_attachments/recordedit.js, and add the function to the file.

The second step is to ensure that the document is loaded, and the updatecontacts() function is called to display the current contact list. jQuery makes this easy by providing a ready() function on the document. Everything within the function you assign to this operation will be executed when the document has finished loading. You can see the definition in Listing 9.


Listing 9. ready() function

$(document).ready(function() {

updatecontacts();

}

Push the application again, and reload the index page. There shouldn't be any changes to what is displayed, but it is good practice to ensure that the application has not been broken when adding in new components.

Of course, the list will still be empty, so let's create a form that can be used to view some contacts.

4 of 9 | Previous | Next

Comments



static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source, Web development
ArticleID=651098
TutorialTitle=Building CouchApps
publish-date=05032011
author1-email=mc@mcslp.com
author1-email-cc=