CouchDB: Create Document
In our previous tutorial, we have learned how to create a database in CouchDB. But before we add any data to it, we need to know that unlike in relational database systems (RDBs), a CouchDB database do not have tables. Instead, data is stored in JSON format, comprising of key/value pairs, known as documents.
Now consider a book, say, A Voyage to Arcturus by David Lindsay. We will learn how to store its details like title and author as a document in the books
database we created in our previous tutorial.
Create Document in Fauxton
Click on the "Create Document" button located just below the right side of the top bar of your Fauxton interface.
As soon as you click, you will notice that the _id
field is auto-created with a 32-character hexadecimal string value, known as the UUID (you can change this later if you wish to). This is the document ID and is unique to the books
database.
Now let us go about storing the title of the book first in the new document. Type a new field just below the auto-generated id
field with name title
and the correspponding value as A Voyage to Arcturus
.
Click the " Create Document" button to save our newly created document data. Another new field called _rev
is created. _rev
is the revision ID and will have a new value everytime you change any field of the document.
This way, we can create additional fields to store additional data. The corresonding field value can be a string, a number, an object or an array.
We add another field named author
to our existing document with the value David Lindsay
. Click the "Save Changes" button.
Notice that the value of _rev
is changed again.
Create Document using cURL
As with creating a database, creating a document using cURL also requires the PUT method. And when we use a method other than GET, we also need to use the -X
option. We will store the details of another book Out of the Silent Planet by C. S. Lewis as a new document in our books
database. Assuming that your CouchDB still runs on localhost (http://127.0.0.1:5984/
), we achieve it with the below command
sudo curl -X PUT http://127.0.0.1:5984/books/02 -d
'{"title": "Out of the Silent Planet","author":"C. S. Lewis"}'
where 02
is some document ID you provided in place of the auto-generated 32-character hexadecimal character.
On successful creation of the document, we get the JSON response:
{"ok": ture, "id": 02, "rev": "1-5ef87b12352f880f8ed4b09483c35a34"}
If you navigate to the books
database in Fauxton, you will find the newly created document.