Working with CouchDB using the Todo List JavaScript application example

At some point in time I had to work with one of the document-oriented DBMSs - Apache CouchDB, but I had difficulty finding documentation. In this article I want to talk about how to work in this DBMS from JavaScript using the small Todo List application as an example. Since the article is focused on ApacheCouchDB, I will not show and talk about how the application works in full.

Model


The principle of operation of this application is as follows:

1. When loading a page, we send a request to the database server.
2. Get the JSON structure from it.
3. Parsim it to the page.
4. If necessary, add any records ...
5. When you click on the "Save" button, write the data to the database.

All page content is stored as follows:

model = {   
	items: [
        {
        _id: 1,
        date: "11.11.11", 
        name: "Тестовый лист 1", 
        does:[{
            check : 'true',
            name : 'Тест 1',
            time : '00:00'
          }]
      }
        { 
        _id: 2, 
        date: "11.11.11", 
        name: "Тестовый лист 2 ", 
        does:[{
            check : 'true', 
            name : 'Тест 2 ', 
            time : '00:00'
        }]
    }
    ]
    }

Each of the items items stores a sheet that includes a to-do list, in the example above, each list contains one item (does).

So we have a model for storing data. The next step is directly working with the DBMS

Install CouchDB


The easiest way to install CouchDB is to go to the website and download the installation distribution for your operating system.

Health Check
After installing CouchDB, you need to check it for health, for this you need to go to the address: 127.0.0.1 : 5984. After making sure that you received the following in response:

image

You can proceed to the next step.

Control Panel


Work with the CouchDB control panel is carried out using the Futon interface, which can be accessed by entering the following address in the address bar of your browser: 127.0.0.1 : 5984 / _utils

If everything is correct, the control panel will appear in front of you (in version 2.xx the control panel looks otherwise).

image

We click on the “Create Database” button and enter the name of our database in the field.

image

Everything is created on this basis, the next step is to interact with this database specifically from the application.

Interaction with the database from the application


I wrote the functional part of the application, without connecting to the database, that is, it works offline, after reloading the page, all data is erased. We need to write the created data to the database, and extract it from there when the application loads.
After combing through the official documentation, I found a plugin written for pure JavaScript, as well as for jQuery. I decided to use JQueryPlugin.

It is located in the CouchDB assembly that we downloaded, you can find it at the address 127.0.0.1 : 5984 / _utils / script / jquery.couch.js

Writing data to the database


After the application creates a model of our data, we need to write them to the database. First of all, you need to specify the host and port of the database:

$.couch.urlPrefix = "http://localhost:5984";

To access the database, use the following function

$.couch.db(“todo_model”).method

We need the saveDoc method - which overwrites the document in the database if it has the same id as the document at the input and creates a new one if the id does not match any of the existing ones.

Next, you need to cycle through each element of the application model, and write it to the database.

for(var i = 0; i < $scope.list.items.length; i++){               
                var doc = $scope.list.items[i];
                doc._id = String(doc._id);
            $.couch.db("todo_model").saveDoc(doc, {
                    success: function(data) {
                        console.log(data);
                        },
                    error: function(status) {
                        console.log(status);
                        }
});       
}

* The application was built using the AngularJS framework. For real purposes, it is not recommended to use AngularJS and jQuery in conjunction.

The database has documents that are stored in JSON format.

image

Thus, using the JQueryCouchDB plugin, you can easily write data to the database. You can also get them from there, but I decided to show a slightly different method that can be used without connecting any third-party plug-ins.

HTTP request to CouchDB


When loading the page, I send a request to the server where our database is located, in response I get a JSON structure with the necessary data:

 $http.get('http://127.0.0.1:5984/todo_model/_all_docs').then(function(response){      //Посылаю запрос на сервер          
                $scope.model_len = response.data.rows.length // Считываю количество элементов
                for (var i = 0; i < $scope.model_len; i++) {
                    var p = response.data.rows[i].id                     // Считываю id каждого элемента
                    $http.get('http://127.0.0.1:5984/todo_model/' + p ).then(function(data){ // Запрашиваю у сервера документ с конкретным id
                        model.items.push(data.data)            
                  });
             }
       });    

I get all the elements to fix their number, after which each of the elements I “push” into the model.

Conclusion


There is little documentation on this DBMS, I showed one way to work with it, and I hope someone helped.

Also popular now: