Skip to content Skip to navigation

Connexions

You are here: Home » Content » Storing JSON documents in a couchDB

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Storing JSON documents in a couchDB

Module by: Hannes Hirzel. E-mail the author

Summary: In this module examples are given how to store, retrieve and update a JSON (JavaScript Object Notation) document in a couchDB instance. Client side JavaScript in a Firefox 'scratchpad' workspace is used.

Introduction

This module demonstrates how JSON documents may be stored, retrieved and updated using JavaScript. For this the Firefox scratchpad is used. However the code snippets provided may be easily adapted for other purposes.

What is a JSON document?

JSON means JavaScript Object Notation. It is used to describe data objects. More on this in the module JavaScript Object Notation.

We take an example document from that module:


var myDict = {};  // create a new instance of Object

myDict["red"] = "rot";
myDict["blue"] = "blau";
myDict["yellow"] = "gelb";
myDict["green"] = "grün";
myDict["white"] = "weiss";
myDict["brown"] = "braun";
myDict["black"] = "schwarz";


JSON.stringify(myDict, undefined, 4)/*

{
    "red": "rot",
    "blue": "blau",
    "yellow": "gelb",
    "green": "grün",
    "white": "weiss",
    "brown": "braun",
    "black": "schwarz"
}
*/

Storing a document for the first time

Document identification

Each document in a couchDB database instance needs an identification. It can be anything but must be unique in the database. Often GUIDs (or UUIDs) are used.

Document revision number

couchDB assigns a document revision number to each document. Old versions are kept. The attribute name used is _rev.

PUT

By using the Http PUT request with an identification a JSON object may be stored for the first time in a database. Here colorDictionary is used as identification.

// prepare request
   var req = new XMLHttpRequest();
   req.open("PUT", "../colorDictionary", false);  // request type, URL, asynchronous = false
   var mimeType="application/json";
   req.setRequestHeader('Content-Type', mimeType); 
   
   console.log("Object to put in couchDB");   // print out the object on the console
   console.log(JSON.stringify(myDict, undefined, 4));  // use pretty printing   
   
   req.send(JSON.stringify(myDict));  // send the JavaScript object as a string.

Firefox scratchpad - storing an object the first time in couchDB

As the answer to the request couchDB gives buck a responseText. It contains the string version of a result JSON object. If the storing operation was successful that object has an attribute "ok" which is then true.

The same code as above without comments and relying on default values for the mime type. The identification used here is "colorDictionary2".


   var req = new XMLHttpRequest();
   req.open("PUT", "../colorDictionary2", false);  
   req.send(JSON.stringify(myDict)); 

POST without a key

When you do not want to provide an identification value for the JSON object to be stored you need to use the Http POST request. The couchDB instance will then automatically assign an identification key.

var req = new XMLHttpRequest();
   req.open("POST", "../", false);  
   req.setRequestHeader('Content-Type', "application/json"); 
   req.send(JSON.stringify(myObj)); 
   
Here it is compulsory to set the header information, otherwise there req.responseText will contain an error message. The database system assigns an identification to the document stored. This identification is given back in req.responseText.

Retrieving a document

The http GET command is used.

var url="../colorDictionary";

var request = new XMLHttpRequest();

request.open("GET", url, false);   //  asynchronous = false

request.send(null);

request.responseText

retrieving a document from couchDB, done in Firefox scratchpad

Further reading

Asynchronous operation

In this module the document was stored in synchronous mode. Normally people use the asynchronous mode. A module which shows that is in preparation.

Updating a document

To update a document the document has to be retrieved first, the attributes updated and then stored again. Module with the example above is in preparation.

Content actions

Download module as:

PDF | EPUB (?)

What is an EPUB file?

EPUB is an electronic book format that can be read on a variety of mobile devices.

Downloading to a reading device

For detailed instructions on how to download this content's EPUB to your specific device, click the "(?)" link.

| More downloads ...

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks