Apache CouchDB is a new database management system (DBMS) in the NoSQL movement. The main information is stored as a JavaScript Object Notation (JSON) document. CouchDB also supports more generic document formats as managed attachments. What it does not support is the classic table data, which is SQL query data and has dominated the DBMS for decades. Another key feature of CouchDB is that all its operations can be used through simple HTTP calls, especially in REST (indicating status transmission). This architecture makes CouchDB easy to use, regardless of your host platform or toolkit. It also makes CouchDB a useful tool for providing a durable back end for websites and applications.
You can find several tutorials to start using CouchDB's built-in JavaScript library and related tools, such as CouchApp (see Related topics ). In this article, I have adopted different methods to show that CouchDB can be combined with a simple static service website support to quickly build a website prototype.
In short
REST is an architectural style for loosely coupled Web applications that relies on named resources (not messages) that depend on named resources (uniform resource locator (URL), UniformResource identifier (URI), and uniform resource name (URN)). REST leverages aspects of the HTTP infrastructure protocol of the world wide Web, such as GET and POST requests.
Bootstrap is a popular new method to quickly build the front end of a website. The bootstrap system was developed by Twitter engineers to help tame the zoo of the platforms and toolkits they use for website development. Bootstrap provides a consistent framework for Web application UI. It can easily use cascading style sheet (CSS) elements to design beautiful websites. These elements are used for layout, forms, buttons, tables, grids, navigation, alerts, etc. In this article, learn to use bootstrap as the front end and CouchDB as the back end to start the development process, even for complex Web applications.
Why not prototype completely on the CouchDB stack?
Although many tutorials have shown that it is easy to develop a complete production site entirely on CouchDB, this is not recommended. Getting started in this way will greatly tempt people to cut corners and use the same method when the website is open. From a security and maintenance point of view, it is best to separate the database back end from the presentation front end. This article provides you with a variety of options for locking CouchDB instances when they are online to protect all sensitive data. Security always requires vigilance and expertise. Because static file based websites have been used for the longest time, it is best to understand them and their management tools are the most mature.
Separating CouchDB from the front end of the website can give you another advantage, because multiple frameworks are often used in the Web development process:
- DBMS for processing data
- Web server or content management system
- Web design framework
In this article, I use CouchDB, Apache HTTP Server, and Bootstrap.
The personnel, skills, and criteria for selecting technology at these levels will usually vary. You want to put one decision with another. In addition to them, you can also move some parts, such as content delivery network, test framework, middleware supporting security, and so on. You can gain more flexibility in mixing and matching these components. In the medium and long term, the system is easier to maintain and improve.
The technology I chose for this article reflects my database management expertise. Apache and Bootstrap are just tools to help me start the application quickly. I hope to cooperate with other experts after the basic knowledge is in place. Middleware developers may prefer to continue using web server frameworks such as Django or Ruby on Rails, or even content management systems such as WordPress, so I use Apache in a way that can be replaced without seriously affecting other layers. Web designers are likely to prefer manual design to Bootstrap, so I use Bootstrap in an easy to replace way. With modern tools and frameworks, prototyping web applications in this way does not rely on a single overall stack, so this is not complicated.
Getting started
Containers that fill pages
The prototype page uses jQuery to load documents from CouchDB into the target div. I use the Ajax functionality of jQuery directly instead of the jQuery plug-in used by CouchDB and CouchApp. The plug-in is very convenient, but it relies on the close integration between CouchDB and the website. The pages of the website are used as database attachments. I prefer to separate them, especially in the development process. Among other things, this allows you to replace another backend as needed. The JavaScript I use to load the page is simple; It takes poquotes JS is included in the code of this article download Medium.
I will present a simple Web Application Demo: a poetry quote website. For help installing CouchDB, see References . Once CouchDB is running on the server, you can download the normal Twitter Bootstrap (just a bundle of CSS and JavaScript) or the complete project bundle. I am using the full bundle in this article.
I get fluid The HTML sample begins. I pruned the file, fixed CSS and JavaScript scripts to delete/ assets/, and updated some static content of the sample site. I saved it as index The results of HTML are in the code package for this article (see download ). Listing 1 is an important part of the HTML page title:
Listing 1 Index Part of the HTML page title
<!-- Styles --> <link href="css/bootstrap.css" rel="stylesheet"> <style type="text/css"> body { padding-top: 60px; padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } </style> <link href="css/bootstrap-responsive.css" rel="stylesheet"> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head>
Listing 2 is index As part of the HTML table, the featured quotation is loaded from CouchDB:
Listing 2 Index Part of an HTML table with quotation marks
<div class="row-fluid"> <div class="span4 featured-quote"> <h2>Poet's name</h2> <p>Body of quote here.</p> <p><a class="btn" href="#">View details »</a></p> </div><!--/span--> <div class="span4 featured-quote"> <h2>Poet's name</h2> <p>Body of quote here.</p> <p><a class="btn" href="#">View details »</a></p> </div><!--/span--> <div class="span4 featured-quote"> <h2>Poet's name</h2> <p>Body of quote here.</p> <p><a class="btn" href="#">View details »</a></p> </div><!--/span--> </div><!--/row-->
The page also includes a mechanism to interact with the database. In particular, the sidebar contains forms that users can use to create new quote records. The user accesses the form by clicking on the link, which triggers jQuery to make the form appear. Listing 3 shows the form tag. (the first two <input> lines are split to fit the page width limits of this article.)
Listing 3 Index for creating new quotation records html forms
<a href="#popup" id="popup">Click to create a new quote</a> <div> <form id="newquote" action="index.html"> <fieldset> <legend>The quote</legend> <label for="author">Author's Name</label> <input id="author" name="author" type="text" placeholder="First and last name" required="required" autofocus="autofocus"> <label for="text">Text of the quotation</label> <input id="text" name="text" type="textarea" placeholder="Text of the quote here" required="required"> </fieldset> <fieldset> <legend>The work</legend> <label for="title">Title of the work</label> <input id="title" name="title" type="text" required="required"> <label for="link">Link to the work</label> <input id="link" name="link" type="text" required="required"> <label for="year">Year of the work</label> <input id="year" name="year" type="text" required="required"> </fieldset> <input id="donewquote" type="submit" value="Add quote" /> </form> </div>
Listing 4 is index The section near the end of the body of the HTML page, which is used to load the necessary JavaScript. The last script line contains specific code for using the poquotes database in CouchDB.
Listing 4 In index Load JavaScript near the end of the body of the HTML page
<!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery-1.7.1.js"></script> <script src="js/bootstrap.js"></script> <script src="js/poquotes.js"></script> </body>
In less than 5 minutes, Bootstrap enabled me to enjoy the basic settings of a website that provides the most modern features, including elegant support on older browsers and mobile devices. For your own website, update colors, fonts, images and other details to suit your design. You can visit the Bootstrap gallery to get a lot of inspiration (see References ).
Prepare data
stay Listing 2 , notice the div element of the div featured quote class. I will load data from CouchDB into those elements. There are six quotation marks on the home page, which are dynamically loaded by the page script and replace the current template.
Go to the CouchDB browser based console Futon (for example, at http:// localhost:5984 / \u utils /), and create a database named poquotes, as shown in Figure 1:
Figure 1 Setting up the poquotes database from the CouchDB Futon page

Listing 5 is a sample document that contains quotation information. (the fourth line is divided into two parts to fit the page width of this article.)
Listing 5 Sample JSON document for quotation marks
{ "type": "quote", "author": "Thomas Hardy", "text": "And as the smart ship grew<br>In stature, grace, and hue<br> In shadowy silent distance grew the Iceberg too.", "work": { "title": "The Convergence Of The Twain", "link": "http://www.poetryfoundation.org/poem/176678", "year": 1915 } }
I use cURL to transfer the file q1 JSON loaded into the new database:
curl -u user:passwd -X POST http://localhost:5984/poquotes \ -H 'Content-Type: application/json' -d @q1.json {"ok":true,"id":"ca42f5a16ca1905978afdeda68c116c2", "rev":"1-7fe040eb6d322a35a86d2f871b100ff0"}
CouchDB's response (beginning with {"ok") indicates that the document has been added, and gives the generated ID and the revision of the new document. CouchDB's RESTful feature makes it almost as easy to prototype the site's dataset as to manipulate the file system. If you like, you can also use Futon to add documents. This article is available for download Sample code Include six such quotation documents - enough to fill the grid of the target page.
Prepare main query
I used Futon to design a view to load the documents needed by the web page. In futon, you can design temporary views, test them, and then save them for practical use. If possible, design the view early in the development cycle, and there are only a few documents in the database, because the temporary view will slow down quickly. Listing 6 is the view JavaScript:
Listing 6 CouchDB view for obtaining all quotation documents, indexed by source working year
function(doc) { if (doc.type == "quote") { emit(doc.work.year, doc); } }
This view is very simple, but it can solve the problem. You can index the results by working year, because this is how I want to sort the records into the page. To add this view to the database, click the view selector and switch to temporary view. Then you can Add Listing 6 Paste into the Map Function box. Click Run to view a list of tables containing six documents. If possible, use the design document name by_year saves the view. It is no longer a temporary view. You can then return to the trusted cURL to execute the view:
curl "http://localhost:5984/poquotes/_design/poquotes/_view/\ by_year?&descending=true&limit=6"
The GET parameter (&descending=true&limit=6) adjusts how the database passes query results. In this case, only the six most recent documents are returned in descending order to ensure that the document with the most recent year field comes first.
Cross domain restrictions
One of the things that makes the loose coupling of multi-layer Web applications and rapid prototyping difficult is a set of cross domain request restrictions in browsers. For security reasons, except for the same port on the same host as the source page, the browser script is strictly restricted and cannot issue HTTP requests. There are several ways to solve this problem. One is to use JSONP (JSON with padding; see References ). Listing 7 is poquotes JS - this section loads the record into the target div:
Listing 7 Load target page JavaScript and jQuery code in quotation marks
... root: "http://localhost:5984/", ... max_quotes: 6, //Invoked when the HTML page is first loaded loadPage: function() { var six_latest = poq.root + "poquotes/_design/poquotes/_view/by_year?&limit=" + poq.max_quotes + "&descending=true&callback=?"; $.getJSON(six_latest, poq.handleMainQuotes); ... }, //Invoked with the result of the Ajax call to load quote documents handleMainQuotes: function(json) { //Load up to six records, as available quote_count = Math.min(poq.max_quotes, json["total_rows"]) for (var i=0; i<quote_count; i++) { var doc = json["rows"][i]["value"] var year = doc["work"]["year"].toString() var title = doc["work"]["title"].toString() var link = doc["work"]["link"].toString() //Create an HTML snippet from the fields of each quote document qblock = $("<div class='span4 featured-quote'></div>") .append("<h2>" + doc["author"] + "</h2>") .append("<p style='font-size: 80%; height: 8em;'>" + doc["text"] + "</p>") .append("<p>" + year + "</p>") .append("<p><a href='" + link + "'>" + title + "</a></p>") .append("<p><a class='btn' href='#'>View details »</a></p>") //jQuery's eq selector to find the target div corresponding to the loop index $('div.featured-quote:eq(' + i.toString() + ')').replaceWith(qblock); } },
stay In Listing 7 , callback=? The file used to load the document is added at the end of the URL. This tells jQuery to use JSONP for Ajax GET queries to extract documents from CouchDB, which is required because the database runs on a different port than the Web front end. This solution is also required if querying databases on other hosts.
Making Ajax requests using methods other than GET is cumbersome. Listing 8 is poquotes JS, poquotes JS is the part that creates a new form and sends it to the database:
Listing 8 JavaScript and jQuery code to transition from form to record and POST its CouchDB
... dbroot: "db/", ... //Invoked when the HTML page is first loaded loadPage: function() { ... $('#donewquote').click(function() { var db_link = poq.dbroot + "poquotes"; var record = { "type": "quote", "author": $("#author").val(), "text": $("#text").val(), "work": { "title": $("#title").val(), "link": $("#link").val(), "year": parseInt($("#year").val()) } }; $.ajax({ url : db_link, data : JSON.stringify(record), contentType : "application/json", type : 'POST', processData : false, dataType : "json", success : function(resp) { alert("New document created: " + JSON.stringify(resp)); } }); return false; }); //Set up the collapsible form for adding new quotes $('#popup').click(function(){ $("#newquote").slideToggle(); }); //Start out with the create quote form collapsed $("#newquote").slideToggle(); },
stay In Listing 8 , POST is performed on the same host and port, but on / db / URL. I use standard techniques to set up a reverse proxy from this URL to the CouchDB host and port. More specifically, I use the Apache HTTP Server ProxyPass directive. The details of this technique depend on your settings, but it is useful when setting up a Web prototype that is strongly separated between the browser and server tiers.
exterior
Figure 2 shows the working example page at the first load after the records in the database are filled in the target div:
Figure 2 Load index Browser screen after HTML

The user can select Click to create a new quotation to display the form for adding a new quotation, as shown in Figure 3:
Figure 3 Index HTML browser screen, displaying forms

epilogue
Throughout this article, I have explained why I prefer certain techniques for prototyping Web applications. They make it easier for Web design and middleware to work on separate parallel tracks, which feels like a natural separation of concerns. I would rather have a dedicated Web server to host the site, even in development, than a DBMS.
In this article, I introduced the details of user authentication and authorization on CouchDB. After the prototyping phase, I will update the middleware to handle user management, sessions, etc. I can forward these questions to the CouchDB organization, or I can use a separate framework based on the project. This is the key flexibility I have gained. Web applications get some details about login and session management, but usually it is a separate layer.
My intention in this article is not to disparage other approaches to prototyping on the NoSQL platform. I offer it as an alternative worth considering. Combined with the most interesting open source projects, each project will focus on its core advantages, which is both interesting and productive. In the process, you will also learn many important details that are often masked by tools that are too tightly coupled.
Translated from: https://www.ibm.com/developerworks/web/library/wa-couchdb-bootstrap/index.html