Couchdb definitive guide chapter 6 companion

.

I’m working through Chris Anderson’s Couchdb Definitive Guide.  I thought I would expand a little on the content of chapter 6.

The chapter starts with 3 documents: “biking”, “bought-a-cat”, “hello-world”.

First, I had to create the database:

curl -X PUT http://127.0.0.1:5984/basic

Then I copied and pasted document content from the guide into 3 .json documents (eg1.json, eg2.json, eg3.json) that I PUT to the database.  The content of the “biking” document looks like this.

{
  "title":"Biking",
  "body":"My biggest hobby is mountainbiking. The other day...",
  "date":"2009/01/30 18:04:11"
}

I asked couchdb for a UUID:

curl -X GET http://127.0.0.1:5984/_uuids

And received a new UUID as .json

{"uuids":["381795b3958bbdd47f1879e8ff000e84"]}

This allowed me to construct a PUT for each egX.json as follows (a new UUID was needed for each document):

curl -X PUT http://127.0.0.1:5984/basic/bd26423be3847a6b7b14e50f36048563 \
-d @egX.json -H 'Content-Type: application/json'

Or, you can let couchdb assign the UUID by using POST:

curl -X POST http://127.0.0.1:5984/basic -d @./CouchApps/egX.json \
-H 'Content-Type: application/json'

Next came the _design/example document.  I initially saved a version 1 and then updated to a version 2 _design/example document.  This is version 1:

{
  "_id" : "_design/example",
  "views" : {
    "foo" : {
      "map" : "function(doc){ emit(doc._id, doc._rev)}"
    }
  }
}

This was PUT to the database:

curl -X PUT http://127.0.0.1:5984/basic/_design/example --data-binary @mydesign.json

Couchdb automatically assigns a revision number to the document that appears within the .json.

And the function foo can be called using:

curl -X GET http://127.0.0.1:5984/basic/_design/example/_view/foo

The next step was to update _design/example with a new function called bar.  The revision number of _design/example was needed:

curl -X GET http://127.0.0.1:5984/basic/_design/example

And this was entered into the  _design/example document

{
  "_id" : "_design/example",
  "_rev" : "1-230141dfa7e07c3dbfef0789bf11773a",
  "views" : {
    "foo" : {
      "map" : "function(doc){ emit(doc._id, doc._rev)}"
    },
    "bar" : {
      "map" : "function(doc) {if(doc.date && doc.title){emit(doc.date, doc.title);}}"
    }
  }
}

_design/example was then updated

curl -vX PUT http://127.0.0.1:5984/basic/_design/example \
-d @./CouchApps/mydesign.json -H 'Content-Type: application/json'

In this example I have used the -d switch, which I think is synonymous with –data-binary, but if an error gets thrown, use –data-binary.  The Content-Type is also required.

Call the bar function like foo before:

curl -X GET http://127.0.0.1:5984/basic/_design/example/_view/bar

Leave a comment