CouchDBRestStore September 26th, 2008 at 6:54 am by Kris Zyp

One of the stores built on JsonRestStore and included in Dojo 1.2 is the new CouchDBRestStore. CouchDB server is a JSON-based schema-free database with clustering and fault-tolerance. This new module utilizes the JsonRestStore RESTful capabilities to interact with a CouchDB server. CouchDB has a standards-based REST interface that integrates well with JsonRestStore via a few adaptions from the CouchDBRestStore modules.

CouchDBRestStore is a subclass of JsonRestStore and therefore supports the same API. Instantiating a CouchDBRestStore to interact with a CouchDB table is very simple, just construct it with the URL of the table:

myStore = new dojox.data.CouchDBRestStore({target:"/MyTable"});

You can now interact with the store using the standard read, write, notification, and identity Dojo Data APIs. Data retrievals trigger queries to the CouchDB server and data modifications are persisted to CouchDB using the standard REST API.

The CouchDBRestStore also provides a method to automatically create a store instance for each table in the CouchDB database. You can get a map of the stores by calling getStores:

var allMyStores = dojox.data.CouchDBRestStore.getStores();

The returned object is a set of properties where the property name is the table name and the property value is the store:

for(var tableName in allMyStores){
   console.log("Table name: ", tableName, "Store:", allMyStores[tableName]);
}
myFavoriteStore = allMyStores.Favorite;

We can now fetch data from a CouchDB table:

myFavoriteStore.fetch({
   query:"_all_docs?startkey=doc2&count=2&descending=true",
   onComplete:function(results){
      // handle the results
   }
});

Or we can do a query using CouchDB’s views:

myFavoriteStore.fetch({
   query:"_view/favorites/veryFavorite",
   onComplete:function(results){
      // handle the results
   }
});

CouchDB sports a schema-free database designed to flexibly persist JSON data and can handle much of the data that can be generated through the Dojo Data API implemented by the store. With JsonRestStore’s full REST capabilities, as well as other features like referencing and direct property access, the CouchDBRestStore is a powerful tool for rapidly prototyping and developing CRUD applications.

Leave a Reply