React/ReactJS and CouchDB (w/ Nano)

You must already be aware of the basic CRUD (Create Read Update Delete) operations that can be performed in CouchDB using Fauxton and/or cURL.

However, integrating CouchDB with other language/framework often necessitates the CRUD operations to be performed programmatically.

For example, if you need to display the info of your CouchDB (up at the usual http://localhost:5984) in your ReactJS component, you need to fetch it programmatically.

									 
				    axios.get('http://localhost:5984')
				      .then(json => console.log(json))					  
				
			

If the server is running, it will give the response:

				
					data: {
						couchdb: "Welcome",
						vendor: {name: "The Apache Software Foundation"},
						version:"2.0.0"
					}
				
			

In this tutorial, we will learn how to perform basic CRUD operations in CouchDB programmatically from ReactJS using nano, a minimalistic CouchDB driver for Node.js. The other popular CouchDB client for Node.js is cradle, but for this tutorial I have picked nano.

Install nano at the root directory of your project.

				
					npm install --save nano
				
			

We will begin by fetching data from an existing CouchDB document. But before we proceed, we need to do some CORS configuration in Fauxton for the hostname (and port) where ReactJS is running.

If your Fauxton is up at http://localhost:5984, go to Config and click on the CORS tab. In the Origin Domains section, you will find the "Restrict to specific domains" button checked by default. If your ReactJS is running at the usual port :3000 in your localhost, type http://localhost:3000 in the input box and click " Add Domain".

1. Fetch a CouchDB Document

In one of our previous tutorials on CouchDB, we created two documents inside the books database, with IDs 2a0580eb69d3153841a74f29c9007d16 and 02. We will fetch the details of the first document with ID 2a0580eb69d3153841a74f29c9007d16.

The nano query for this is:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.db.use('books').get('2a0580eb69d3153841a74f29c9007d16')
				      	.then((body) => {
				      		console.log(body);
				      	});
					
				

If the query is successful, we get the following response in the browser's console:

					
						{
							author:"David Lindsay"
							title:"A Voyage to Arcturus"
							_id:"2a0580eb69d3153841a74f29c9007d16"
							_rev:"2-8d77d98a6b66bc8829f5d2d9fd159eb4"
						}
					
				

2. Create Database in CouchDB

We next get into creating a new database called cars:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.db.create('cars', function(err, body) {
				        if (!err) {
				          console.log(body);
				        }
				      });
					
				

On successful creation of database, we get the below response in the console:

					
						{ok: true}
					
				

If you refresh http://localhost:5984/_utils/#_all_dbs you will find the new database listed in the bottom row.

3. Create Document in CouchDB Database

Now we can store some document data inside our newly created database cars.

Regera by Aab254. CC BY-SA 4.0

We will store the following JSON key-value pair as a document inside it.

					
						{
							name:"Koenigsegg Regera"
						}
					
				

Usually, CouchDB auto-generates a UUID for the document, but we can also specify our own ID for it. Here we assign the ID koenigsegg for the document while creating it:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.use('cars').insert({id:'koenigsegg', name:'Koenigsegg Regera'}, 
				      	function(err, body) {
				        	if (!err)
				          		console.log(body);
				      	});
					
				

The document ID can also be passed as a second argument to the insert() function:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.use('cars').insert({ name: 'Koenigsegg Regera' }, 'koenigsegg', 
				      	function(err, body) {
				        	if (!err)
				          		console.log(body);
				      	});
					
				

On successful creation of document, we get the response:

					
						{
							id:"koenigsegg"
							ok:true
							rev:"1-897c1910cca82e5a8ddfd4d70888d449"
						}
					
				

4. Update Document in CouchDB Database

Now suppose you want to change the value of the name field in the above document; say, you want to replace the value Koenigsegg Regera with Koenigsegg Agera RS. You can still use the insert() document function as above when creating a document, but you need to include another token _rev in the query object:

					
					let obj =  {
						_id: 'koenigsegg',
						_rev: '1-897c1910cca82e5a8ddfd4d70888d449',
						name: 'Koenigsegg Agera RS'
					};
					const nano = require('nano')('http://localhost:5984');
					nano.use('cars').insert(obj, function(err, body) {
						if (!err)
							console.log(body);
					  });
					
				

Notice that the rev value has changed.

					
						{
							id:"koenigsegg"
							ok:true
							rev:"2-0e70e8016b800d269a764fc18a1466bb"
						}
					
				

5. Delete Document from a CouchDB Database

The koenigsegg document can be removed from the cars database by providing its id and rev fields as arguments to the destroy() function:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.use('cars').destroy('koenigsegg', '2-0e70e8016b800d269a764fc18a1466bb', 
				      	function(err, body) {
				      		if (!err)
				          		console.log(body);
				      	});
					
				

The rev field will still show a new value in the response, despite the document being already removed from the database.

					
						{
							id:"koenigsegg"
							ok:true
							rev:"3-e75edfe61b0ea16bc11fe5b2051e6809"
						}
					
				

6. Delete Database from CouchDB

The destroy() method is used to remove a database too:

					
				      const nano = require('nano')('http://localhost:5984');
				      nano.db.destroy('cars');