Pouchdb Tutorial
Pouchdb Tutorial
PouchDB
This tutorial discusses the basics of PouchDB along with relevant examples for easy
understanding.
Audience
This tutorial has been prepared for beginners to help them understand the basic
concepts of PouchDB. It will aid you to build applications which will work offline and
online alike using PouchDB and CouchDB.
Prerequisites
The reader should have a basic knowledge of databases. It would be better to have a
good command on programming languages, which are compatible with node.js such as
JavaScript and CoffeeScript.
Copyright &Disclaimer
Copyright 2016 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point
(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or
republish any contents or a part of contents of this e-book in any manner without written
consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I)
Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of
our website or its contents including this tutorial. If you discover any errors on our
website or in this tutorial, please notify us at contact@tutorialspoint.com
i
PouchDB
Table of Contents
About this Tutorial ................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
ii
PouchDB
iii
PouchDB
Compaction ........................................................................................................................................... 79
iv
1. PouchDB – Overview PouchDB
This chapter provides a brief introduction to PouchDB along with its features and how it
works.
What is PouchDB?
PouchDB is an open source in-browser database API written in JavaScript. It is
modelled after Couch DB – a NoSQL database. Using this API, we can build applications
that work offline and online. It internally uses WebSQL and IndexedDB to store data.
Using PouchDB,you can communicate with both local and remote databases seamlessly
without noticing any difference.
Features of PouchDB
Following are the features of PouchDB -
Cross Browser: The API provided by PouchDB works the same in every
environment, therefore, we can run a PouchDB application in various browsers.
Light Weight: PouchDB is a very light-weight API, it is also included easily just
using a script tag.
Advantages of PouchDB
Following are the advantages of PouchDB –
Since PouchDB resides inside the browser, there is no need to perform queries
over the network, this results in faster execution of queries.
You can synchronize the data with any of the supported server and by doing so
you can run apps both online and offline.
1
PouchDB
2
2. PouchDB – Environment PouchDB
This chapter explains how to download and install PouchDB in your system.
Installing PouchDB
In order to work with PouchDB, you need to download the file .js file and include it in
your script. Following are the steps to install PouchDB.
Step1
Visit the homepage of PouchDB website, by clicking the following link –
https://PouchDB.com/
Step2
Click the Download button on the top right hand side of the web page as shown in the
above screenshot. This will download PouchDB-5.3.0.min.js in your system.
3
PouchDB
Step3
Copy and paste the PouchDB-5.3.0.min.js to your working directory and include it in
your JavaScript as shown in the following command.
<scriptsrc="PouchDB-5.3.0.min.js"></script>
Step1
Install Node.js by following the steps given in the Installing Node.js section of our coffee
script tutorial.
Step2
Open the command prompt and execute the following command. This will install
PouchDB node module in your system.
Downloading CouchDB
When offline, PouchDB stores data locally and works like an app. You can access it online
by connecting with compatible servers. As we know PouchDB can be connected to
CouchDB, so, lets install CouchDB too. Following are the steps to install CouchDB.
Step1
The official website for CouchDB is http://couchdb.apache.org. If you click the given link,
you can get the home page of CouchDB official website as shown in the following
screenshot.
4
PouchDB
Step 2
If you click on the download button that will lead to a page where the download links of
CouchDB in various formats are provided. The following snapshot illustrates the same.
5
PouchDB
Step 3
Choose the download link for Windows Systems and select one of the provided mirrors to
start your download.
Installing CouchDB
A windows executable setup-couchdb-1.6.1_R16B02.exe file will be downloaded on
your system. Run the setup file and proceed with the installation.
After installing CouchDB in your system successfully, open the folder where CouchDB
was installed, go to the bin folder, and start the server by running a script file named
couchdb.bat.
After installation, open built-in web interface of CouchDB by visiting the following link:
http://127.0.0.1:5984/. If everything goes fine, this will give you a web page, which will
have the following output.
{ "couchdb":"Welcome","uuid":"c8d48ac61bb497f4692b346e0f400d60",
"version":"1.6.1",
"vendor":{
"version":"1.6.1","name":"The Apache Software Foundation"
}}
You can interact with CouchDB web interface by using the following URL –
http://127.0.0.1:5984/_utils/
This shows you the index page of Futon, which is the web interface of CouchDB.
6
3. PouchDB– Create Database PouchDB
Syntax
Following is the syntax of using the PouchDB constructor. To this, you need to pass the
name of the database as a parameter.
New PouchDB(Database_name)
Example
To create a database in PouchDB using node, first of all, you need to require the
PouchDB package using the require() method and then you can create a database as
shown in the following example.
Save the above code in a file with the name Create_Database.js. Open the command
prompt and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Create_Database.js
This will create a database locally (you can see the folder in the current directory)
displaying the following message.
7
4. PouchDB –Database Info PouchDB
You can get the basic information about the database using the method named info()
Syntax
Following is the syntax of using the info() method of PouchDB. This method accepts a
callback function.
db.info([callback])
Example
Following is an example of retrieving database information using the info() method.
Here, we are displaying the information of the database named my_database. In case
of error, the error will be displayed on the console.
//Database information
db.info(function(err, info) {
if (err) {
return console.log(err);
} else {
console.log(info);
}
});
Save the above code in a file with the name Database_info.js. Open the command
prompt and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Database_info.js
8
PouchDB
{ doc_count: 0,
update_seq: 0,
backend_adapter: 'LevelDOWN',
db_name: 'my_database',
auto_compaction: false,
adapter: 'leveldb' }
Example
Following is an example of retrieving information of a database that is saved in the
CouchDB server. This code gives you information of a database named my_database.
//Database information
db.info(function(err, info) {
if (err) {
return console.log(err);
} else {
console.log(info);
}
});
Save the above code in a file with the name Database_Remote_info.js. Open the
command prompt and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Database_remote_info.js
{ db_name: 'my_database',
9
PouchDB
doc_count: 0,
doc_del_count: 0,
update_seq: 0,
purge_seq: 0,
compact_running: false,
disk_size: 79,
data_size: 0,
instance_start_time: '1458209191708486',
disk_format_version: 6,
committed_update_seq: 0,
host: 'http://localhost:5984/my_database/',
auto_compaction: false,
adapter: 'http' }
10
5. PouchDB –Delete Database PouchDB
Syntax
Following is the syntax of using the db.destroy() method. This method accepts a
callback function as a parameter.
db.destroy()
Example
Following is an example of deleting a database in PouchDB using the destroy() method.
Here, we are deleting the database named my_database, created in the previous
chapters.
//deleting database
db.destroy(function (err, response) {
if (err) {
return console.log(err);
} else {
console.log ("Database Deleted”);
}
});
Save the above code in a file with the name Delete_Database.js. Open the command
prompt and execute the JavaScript file using node as shown below.
This will delete the database named my_database which is stored locally displaying the
following message.
Database Deleted
11
PouchDB
Deleting a RemoteDatabase
In the same way, you can delete a database that is stored remotely on the server
(CouchDB).
To do so, instead of a database name, you need to pass the path to the database that is
required to be deleted, in CouchDB.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
//deleting database
db.destroy(function (err, response) {
if (err) {
return console.log(err);
} else {
12
PouchDB
console.log("Database Deleted");
}
});
Save the above code in a file with the name Remote_Database_Delete.js. Open the
command prompt and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Remote_Database_Delete.js
This deletes the specified database from PouchDB displaying the following message.
Database Deleted
Verification
After executing the above program, if you visit the URL again, you will get the following
screenshot. Here you can observe only two databases since my_database was deleted.
13
6. PouchDB – Create Document PouchDB
Syntax
Following is the syntax of using the db.put() method of PouchDB. You can store the
document that is to be created in PouchDB, in a variable and pass as a parameter to this
method. In addition, this method also accepts a callback (optional) function as a
parameter.
db.put(document, callback)
Example
Following is an example of creating a document in PouchDB using the put() method.
The document we create should be of JSON format, a set of key-value pairs separated
by comma (,) and enclosed within curly braces ({}).
14
PouchDB
Save the above code in a file with name Create_Document.js. Open the command
prompt and execute the JavaScript file using node as shown below.
This creates the given document in PouchDB database named my_database, which is
stored locally, displaying the following message.
To do so, instead of database name you need to pass the path to the database where
you want to create documents in CouchDB.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
Now, if you click on the database named my_database, you will find an empty
database as shown in the following screenshot.
15
PouchDB
16
PouchDB
Save the above code in a file with the name Remote_Create_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This creates the given document in PouchDB database named my_database which is
stored in CouchDB, displaying the following message.
Verification
After executing the above program, if you visit the my_database again, you can
observe the document created as shown in the following screenshot.
17
7. PouchDB – Read Document PouchDB
You can read/retrieve the contents of a document in PouchDB using the db.get()
method.
Syntax
Following is the syntax of using the db.get() method of PouchDB. This method accepts
the document id and an optional callback function.
Example
Following is an example of reading the contents of a document in PouchDB using the get
() method.
Save the above code in a file with name Read_Document.js. Open the command
prompt and execute the JavaScript file using node as shown in the following command.
This reads the contents of the given document that exists in the database named
my_database which is stored locally. The following message gets displayed on the
console.
18
PouchDB
{name: 'Raju',
age: 23,
designation: 'Designer',
_id: '001',
_rev: '1-ba7f6914ac80098e6f63d2bfb0391637'}
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose, there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
By clicking on the database named my_database you can see the following screenshot.
Here, you can observe that this database contains a document with id 001.
19
PouchDB
Following is an example of reading the contents of the document having id as “001” that
exists in a database named my_database, which is stored in the CouchDB server.
20
PouchDB
Save the above code in a file with the name Remote_Read_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This reads the contents of the given document that exists in the database named
my_database which is stored in CouchDB. The following message is displayed on the
console.
{ _id: '001',
_rev: '3-552920d1ca372986fad7b996ce365f5d',
name: 'Raju',
age: 23,
designation: 'Designer' }
21
8. PouchDB – Update Document PouchDB
You can update an existing document in PouchDB using the (_rev). To do so, first of all
retrieve the _rev value of the document we want to update. Now, place the contents
that are to be updated along with the retrieved _rev value in a new document, and
finally insert this document in PouchDB using the put() method.
Example
Assume we have a document in PouchDB with id 001 which has details of a person. In
order to update this document, we should have its rev number. Therefore, to retrieve
the contents of the document the following code is used.
On executing the above code, you will receive the following output.
{ _id: '001',
_rev: '3-552920d1ca372986fad7b996ce365f5d',
name: 'Raju',
age: 23,
designation: 'Designer' }
22
PouchDB
Now, using the _rev you can update the value of the key “age” to 26, as shown in the
following code.
//Inserting Document
db.put(doc);
Save the above code in a file with the name Update_Document.js. Open the command
prompt and execute the JavaScript file using node as shown below.
C:\Pouch_Examples>node Update_Document.js
This updates the contents of the given document that exists in the database named
my_database which is stored locally. The following message is displayed on the
console.
{ name: 'Raju',
age: 26,
designation: 'Designer',
_id: '001',
_rev: '2-61b523ccdc4e41a8435bdffbb057a7a5' }
23
PouchDB
To do so, instead of a database name you need to pass the path to the database in
CouchDB, which contains the document that is to be updated.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
By clicking on the database named my_database, you can see the following
screenshot. Here, you can observe that this database contains a document with id 001.
24
PouchDB
Following is an example of updating the age of the document having id as “001” that
exists in a database named my_database which is stored in the CouchDB server.
25
PouchDB
Save the above code in a file with the name Remote_Update_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This updates the contents of the given document that exists in the database named
my_database which is stored in CouchDB. The following message is displayed on the
console.
{ _id: '001',
_rev: '2-b9640bffbce582c94308905eed8bb545',
name: 'Raju',
age: 26,
designation: 'Designer' }
26
9. PouchDB – Delete Document PouchDB
You can delete a document from a database that exists in PouchDB using the
db.remove() method.
Syntax
Following is the syntax of using the db.remove() method of PouchDB. To this method,
we have to pass id and _rev to delete an existing document as shown in the following
code. This method accepts an optional callback function. We can also pass the complete
document instead of id and _rev.
Example
Assume we have a document in PouchDB with id 001which have the details of a person.
In order to delete this document along with its id we should also have its _rev number.
Therefore, retrieve the contents of the document as shown in the following code.
{ _id: '001',
27
PouchDB
_rev: '3-552920d1ca372986fad7b996ce365f5d',
name: 'Raju',
age: 23,
designation: 'Designer' }
Now, using the _rev and id of the document you can delete this by using the remove()
method as shown in the following code.
Save the above code in a file with the name Delete_Document.js. Open the command
prompt and execute the JavaScript file using node as shown below.
This deletes the contents of the given document that exists in the database named
my_database which is stored locally. The following message is displayed.
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
28
PouchDB
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
By clicking on the database named my_database you can see the following screenshot.
Here, you can observe that the database contains a document with id 001.
Following is an example of deleting the contents of the document having id “001” that
exists in a database named my_database which is stored in the CouchDB server.
29
PouchDB
Save the above code in a file with name Remote_Delete_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This deletes the given document that exists in the database named my_database which
is stored in CouchDB. The following message is displayed.
30
10. PouchDB – Create Batch PouchDB
You can create an array (batch) of documents in PouchDB using the db.bulkDocs()
method. While creating documents, using this method if we do not provide _id values,
on our behalf PouchDB generates unique ids for all the documents in the bulk.
Syntax
Following is the syntax of using the db.bulkDocs() method of PouchDB. You can store
all the documents that are to be created in PouchDB in an array and pass it to this
method as a parameter. In addition to it, this method also accepts a callback (optional)
function as a parameter.
Example
Following is an example of creating multiple documents in PouchDB using the
db.bulkDocs () method. The documents we create should be of JSON format, a set of
key-value pairs separated by comma (,) and enclosed within curly braces ({}).
//Inserting Documents
db.bulkDocs(docs, function(err, response) {
if (err){
return console.log(err);
} else {
console.log("Documents created Successfully");
}
});
31
PouchDB
Save the above code in a file with name Create_Batch.js. Open the command prompt
and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Create_Batch.js
This creates the given document in PouchDB database named my_database which is
stored locally. The following message gets displayed.
To do so, instead of a database name you need to pass the path to the database where
we want to create documents in CouchDB.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
32
PouchDB
//Inserting Documents
db.bulkDocs(docs, function(err, response) {
if (err){
return console.log(err);
} else{
console.log("Documents created Successfully");
}
});
Save the above code in a file with the name Remote_Create_Batch.js. Open the
command prompt and execute the JavaScript file using node as shown below.
C:\PouchDB_Examples>node Remote_Create_Batch.js
This creates the given documents in PouchDB database named my_database which is
stored in CouchDB. The following message is displayed.
33
PouchDB
Verification
After executing the above program if you visit the my_database again, you can observe
the documents created as shown in the following screenshot.
34
11. PouchDB – Fetch Batch PouchDB
You can read/retrieve multiple/bulk documents from a database in PouchDB using the
allDocs() method.
Syntax
Following is the syntax of using the db.allDocs() method of PouchDB. This method
accepts an optional callback function.
db. allDocs()
Example
Following is an example of retrieving all the documents in a database named
my_database that is stored locally, using db.allDocs() method. This method retrieves
the array of documents in the form of objects, to get the contents of each document you
need to call as docs.rows.
Save the above code in a file with the name Read_All_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This reads all the documents that exists in the database named my_database which is
stored locally. The following message is displayed on the console.
35
PouchDB
[ { id: '001',
key: '001',
value: { rev: '1-9dc57f5faa7ea90eeec22eba8bfd05f5' } },
{ id: '002',
key: '002',
value: { rev: '1-9bf80afcedb9f8b5b35567292affb254' } },
{ id: '003',
key: '003',
value: { rev: '1-1204f108e41bf8baf867856d5da16c57' } }]
In general, as shown in the above result, using allDocs() method you can see only the
_id, key and _rev fields of each document. However, to include the whole document in
the result, you have to make the optional parameter include_docs true as shown
below.
Executing the above code gives you a list of complete documents in the specified
documents as shown in the following code.
[ { id: '001',
36
PouchDB
key: '001',
value: { rev: '1-9dc57f5faa7ea90eeec22eba8bfd05f5' },
doc:
{ name: 'Ram',
age: 23,
Designation: 'Programmer',
_id: '001',
_rev: '1-9dc57f5faa7ea90eeec22eba8bfd05f5' } },
{ id: '002',
key: '002',
value: { rev: '1-9bf80afcedb9f8b5b35567292affb254' },
doc:
{ name: 'Robert',
age: 24,
Designation: 'Programmer',
_id: '002',
_rev: '1-9bf80afcedb9f8b5b35567292affb254' } },
{ id: '003',
key: '003',
value: { rev: '1-1204f108e41bf8baf867856d5da16c57' },
doc:
{ name: 'Rahim',
age: 25,
Designation: 'Programmer',
_id: '003',
_rev: '1-1204f108e41bf8baf867856d5da16c57' } }]
To do so instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
37
PouchDB
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
Following is an example of reading all the documents that exist in a database named
my_database which is stored in the CouchDB server.
38
PouchDB
Save the above code in a file with the name Remote_Read_AllDocument.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This reads the contents of the given document that exists in the database named
my_database which is stored in CouchDB, and displays on the console as shown below.
[ { id: '001',
key: '001',
value: { rev: '3-552920d1ca372986fad7b996ce365f5d' },
doc:
{ _id: '001',
_rev: '3-552920d1ca372986fad7b996ce365f5d',
name: 'Raju',
age: 23,
designation: 'Designer' } },
{ id: '002',
key: '002',
value: { rev: '1-9af15cb11054ebe03a7816bf6c5e4128' },
doc:
{ _id: '002',
_rev: '1-9af15cb11054ebe03a7816bf6c5e4128',
name: 'Robert',
age: 24,
Designation: 'Programmer' } },
{ id: '003',
key: '003',
value: { rev: '1-3033b5a78e915c52fd37325d42eb3935' },
doc:
{ _id: '003',
_rev: '1-3033b5a78e915c52fd37325d42eb3935',
name: 'Rahim',
age: 25,
Designation: 'Programmer' } } ]
39
12. PouchDB – Update Batch PouchDB
You can update an array of documents in PouchDB at once using the bulkDocs()
method. To do so you need to create an array of documents where, each document
contains _id, _rev and the values are to be updated.
Suppose the database named my_database that is stored locally in PouchDB contains 3
documents namely doc1, doc2, doc3 with the following contents.
Suppose we have to increase the age values in all the 3 documents by 2 years. For this
to happen, first you need to get the _rev values. Therefore, fetch the contents of these
documents using the following code.
Save the above code as bulk_fetch.js. On executing, the above program gives you the
_id and _rev values of the documents in the database as shown below.
[ { id: '001',
key: '001',
value: { rev: '1-1604b0c3ff69dc1e261265fd60808404' } },
{ id: '002',
key: '002',
40
PouchDB
Now, you can update the documents using their respective _id and _rev values as
shown below.
Save the above code in a file with the name Update_All_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This updates all the documents that exists in the database named my_database which
is stored locally, displaying the following message.
41
PouchDB
[ { id: '001',
key: '001',
value: { rev: '2-77f3a9974dd578d12f3f2a33aae64c8d' },
doc:
{ age: 25,
_id: '001',
_rev: '2-77f3a9974dd578d12f3f2a33aae64c8d' } },
{ id: '002',
key: '002',
value: { rev: '2-43966007568ce9567c96422195fcfa0d' },
doc:
{ age: 26,
_id: '002',
_rev: '2-43966007568ce9567c96422195fcfa0d' } },
{ id: '003',
key: '003',
value: { rev: '2-6c5349652527f4f39583ff14f23cd677' },
doc:
{ age: 27,
_id: '003',
_rev: '2-6c5349652527f4f39583ff14f23cd677' } } ]
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
42
PouchDB
And assume if we select the database named my_database, you can observe that it
contains 3 documents as shown in the following screenshot.
Now, fetch the contents of these documents using the following code.
43
PouchDB
Save the above code as remote_bulk_fetch.js. On executing, the above program gives
you the contents of all the documents in the database as shown below.
[ { id: '001',
key: '001',
value: { rev: '3-552920d1ca372986fad7b996ce365f5d' },
doc:
{ _id: '001',
_rev: '3-552920d1ca372986fad7b996ce365f5d',
name: 'Raju',
age: 23,
designation: 'Designer' } },
{ id: '002',
key: '002',
value: { rev: '1-9af15cb11054ebe03a7816bf6c5e4128' },
doc:
{ _id: '002',
_rev: '1-9af15cb11054ebe03a7816bf6c5e4128',
name: 'Robert',
age: 24,
Designation: 'Programmer' } },
{ id: '003',
key: '003',
value: { rev: '1-3033b5a78e915c52fd37325d42eb3935' },
doc:
{ _id: '003',
_rev: '1-3033b5a78e915c52fd37325d42eb3935',
44
PouchDB
name: 'Rahim',
age: 25,
Designation: 'Programmer' } } ]
Following is an example of updating all the documents that exists in a database named
my_database which is stored in the CouchDB server.
//Inserting Document
db.bulkDocs(docs, function(err, response) {
if (err){
return console.log(err);
} else {
console.log(+"Documents Updated Successfully");
}
});
Save the above code in a file with the name Remote_Update_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This updates the contents of all given document that exists in the database named
my_database which is stored in CouchDB, and displays the following message.
Now, if you execute the remote_bulk_fetch.js program you will can see the values of
the documents updated, as shown below.
[ { id: '001',
45
PouchDB
key: '001',
value: { rev: '4-6bc8d9c7a60fed2ed1667ec0740c1f39' },
doc:
{ _id: '001',
_rev: '4-6bc8d9c7a60fed2ed1667ec0740c1f39',
age: 25 } },
{ id: '002',
key: '002',
value: { rev: '2-1aa24ce77d96bb9d2a0675cdf1e113e0' },
doc:
{ _id: '002',
_rev: '2-1aa24ce77d96bb9d2a0675cdf1e113e0',
age: 26 } },
{ id: '003',
key: '003',
value: { rev: '2-fa113149ba618eda77f73072974a2bc1' },
doc:
{ _id: '003',
_rev: '2-fa113149ba618eda77f73072974a2bc1',
age: 27 } } ]
46
13. PouchDB – Delete Batch PouchDB
You can delete an array of documents in PouchDB at once using the bulkDocs()
method. To do so you need to create an array of documents that are to be deleted
where, each document should contain _id and _rev. In addition to these you have to
add another key-value pair _deleted: true.
Suppose the database named my_database that is stored locally in PouchDB contains 3
documents namely doc1, doc2, doc3 with the following contents.
And say, we have to delete all the three documents. Then, first of all you need to get
their _rev values. Therefore, fetch the contents of these documents using the following
code.
47
PouchDB
Save the above code as bulk_fetch.js. Executing the above program gives you the _id
and _rev values of the documents in the database as shown below.
[ { id: '001',
key: '001',
value: { rev: '1-1604b0c3ff69dc1e261265fd60808404' } },
{ id: '002',
key: '002',
value: { rev: '1-b5e49db7e984841bf12a13e3ee548125' } },
{ id: '003',
key: '003',
value: { rev: '1-a7b342786ecc707aa91f3b321a177b51' } } ]
Now, you can delete the documents using their respective _id and _rev values as shown
below.
//Deleting Documents
db.bulkDocs(docs, function(err, response) {
if (err){
return console.log(err);
} else{
console.log(response+"Documents deleted Successfully");
}
});
Save the above code in a file with the name Delete_All_Document.js. Open the
command prompt and execute the JavaScript file using node as shown below.
48
PouchDB
This deletes all the documents that exists in the database named my_database which is
stored locally, displaying the following message.
Now, if you execute the bulk_fetch.js program, you can observe an empty brace on the
console indicating that the database is empty, as shown below.
[]
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
If we select the database named my_database, you can observe that it contains 3
documents as shown in the following screenshot.
49
PouchDB
Following is an example of deleting all the documents that exist in a database named
my_database which is stored in the CouchDB server.
Save the above code in a file with name Remote_delete_AllDocuments.js. Open the
command prompt and execute the JavaScript file using node as shown in the following
screenshot.
50
PouchDB
This deletes the contents of all given document that exists in the database named
my_database which is stored in CouchDB, and displays the following message.
51
14. PouchDB – Adding Attachment PouchDB
You can attach a binary object to a document using the putAttachment() method in
PouchDB.
Syntax
Following is the syntax of the putAttachment(). To this method, we have to pass the
document id, attachment id, MIME type along with the attachment. This method also
accepts an optional callback function.
We can prepare attachment using blob or buffer objects, where blob is used while
working with the browser and buffer is used while working with Node.js, since we are
demonstrating our programs in Node.js, we use buffer objects to prepare documents.
Example
Following is an example of creating a document with an attachment, within a database
named my_database in PouchDB using putAttachment() method.
52
PouchDB
Save the above code in a file with name Add_Attachment.js. Open the command
prompt and execute the JavaScript file using node as shown below.
This creates an empty document adding an attachment to it, in the database named
my_database which is stored in PouchDB, and displays the following message.
You can verify whether the attachment is added by reading the document using the
following code.
Save the above code as read_doc.js and execute it. Executing this program,you can
see the following contents of the document.
{ _attachments:
{ att_1.txt:
{ content_type: 'text/plain',
digest: 'md5-k7iFrf4NoInN9jSQT9WfcQ==',
data: 'AA==' } },
_id: '001',
_rev: '1-620fd5f41d3328fcbf9ce7504338a51d' }
53
PouchDB
{ name: 'Raju',
age: 23,
designation: 'Designer',
_id: '002',
_rev: '1-05ca7b5f3f4762a9fb2d119cd34c8d40' }
Now, you can add an attachment to this document using its _rev value.
rev = '1-05ca7b5f3f4762a9fb2d119cd34c8d40';
db.putAttachment('002','att_1.txt',rev, my_attachment, 'text/plain',
function(err, res) {
if (err) {
return console.log(err);
} else {
console.log (res+"Attachment added successfully")
}
});
Save the above code in a file with the name Add_Attachment_to_doc.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This adds an attachment to the specified document displaying the following message.
If you change the id value in read_doc.js to 002 and execute it, you will get the
following output.
54
PouchDB
{ name: 'Raju',
age: 23,
designation: 'Designer',
_attachments:
{ att_1:
{ content_type: 'text/plain',
digest: 'md5-k7iFrf4NoInN9jSQT9WfcQ==',
data: 'AA==' } },
_id: '002',
_rev: '2-3bb4891b954699bce28346723cc7a709' }
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
And if you select the database named my_database, you can view its contents as
shown below.
55
PouchDB
rev = '1-36c34fdcf29a652876219065f9681602';
db.putAttachment('001', 'att_1.txt',rev, my_attachment, 'text/plain',
function(err, res) {
if (err) {
56
PouchDB
return console.log(err);
} else {
console.log (res+ "Attachment added successfully")
}
});
Save the above code in a file with the name Remote_Add_Attachment.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This adds an attachment to the specified document displaying the following message.
Now, if you verify the document, you can observe the attachment added to it as shown
in the following screenshot.
57
PouchDB
58
15. PouchDB – Retrieving Attachment PouchDB
You can retrieve an attachment from PouchDB using the getAttachment() method.
This method always returns blob or buffer objects.
Syntax
Following is the syntax of the getAttachment(). To this method, we have to pass the
document id and attachment id. This method also accepts an optional callback function.
Example
Following is an example of retrieving an attachment of a document stored in PouchDB,
using getAttachment() method. Using this code, we are trying to retrieve an
attachment att_1.txtfrom the document 001.
Save the above code in a file with the name Retrive_Attachment.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This retrieves the attachment of the document and displays on the console as shown
below.
59
PouchDB
<Buffer 00>
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
If you select the database named my_database, you can view its contents as shown
below.
60
PouchDB
61
PouchDB
Save the above code in a file with the name Remote_Retrieve_Attachment.js. Open
the command prompt and execute the JavaScript file using node as shown below.
This retrieves the document attachment and displays it on the console as shown below.
<Buffer 00>
62
16. PouchDB – Deleting Attachment PouchDB
You can delete an attachment from PouchDB using the removeAttachment() method.
Syntax
Following is the syntax of the removeAttachment() method. To this method, we have
to pass the document id, attachment id, and _rev value. This method also accepts an
optional callback function.
Example
Suppose there is a document in PouchDB with id 001, which contains id, name, age,
designation of an employee along with an attachment as shown below.
{ name: 'Raju',
age: 23,
designation: 'Designer',
_attachments:
{ 'att_1.txt':
{ content_type: 'text/plain',
digest: 'md5-k7iFrf4NoInN9jSQT9WfcQ==',
data: 'AA==' } },
_id: '001',
_rev: '2-cdec6c9f45ddbee7d456945654742d43' }
63
PouchDB
if (err) {
return console.log(err);
}
else {
console.log(res+"Attachment Deleted successfully")
}
});
Save the above code in a file with the name Remove_Attachment.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This removes the attachment of the document and displays a message on the console as
shown below.
After deletion, you can verify the contents of the document by executing the following
code.
64
PouchDB
Save this code as read.js and execute it. On executing, you will get the contents of the
document after deleting the attachment, as shown below.
{ name: 'Raju',
age: 23,
designation: 'Designer',
_id: '001',
_rev: '3-da775487a6ed0495f2e49c543384f8e8' }
To do so, instead of a database name, you need to pass the path to the database in
CouchDB, which contains the document that is to be read.
Example
Suppose there is a database named my_database in the CouchDB server. Then, if you
verify the list of databases in CouchDB using the URL
http://127.0.0.1:5984/_utils/index.html you will get the following screenshot.
And if you select the database named my_database, you can view its contents as
shown below.
65
PouchDB
66
PouchDB
Save the above code in a file with the name Remote_Delete_Attachment.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This removes the existing attachment and displays the following message.
67
PouchDB
If you visit the document again, you can notice that the attachment was deleted as
shown in the following screenshot.
68
17. PouchDB–Replication PouchDB
One of the most important features of PouchDB is replication, i.e. you can make a copy
of a database. You can replicate either a PouchDB instance stored locally or a CouchDB
instance stored remotely.
Syntax
Following is the syntax of replicating a database in PouchDB. Here, a copy of the source
database is the target. To this method, you can directly pass the location of source and
destination databases in String format, or you can pass objects representing them.
Both the source and targets can be either PouchDB instances or CouchDB instances.
69
PouchDB
Save the above code in a file with name Replication_example.js. Open the command
prompt and execute the JavaScript file using node as shown below.
This makes a copy of the database named sample_database in CouchDB instance and
displays a message on the console as shown below.
You can verify whether the database is replicated in your CouchDB instance by clicking
the following link http://127.0.0.1:5984/_utils/index.html.
On clicking, you can see the list of databases in your CouchDB. You can also observe
that a copy of the database sample_database is created here.
If you select the replicated database, you can view its contents as shown below.
70
PouchDB
Save the above code in a file with the name Replication_example2.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This makes a copy of the database named remote_database in PouchDB instance and
displays a message on the console as shown below.
71
PouchDB
You can verify whether the database is replicated in your Pouch instance by executing
the following code.
If the database is replicated on executing the above code, you will get the contents of
the replicated database as shown below.
[ { id: '001',
key: '001',
value: { rev: '1-23cf3767e32a682c247053b16caecedb' },
doc:
{ name: 'Geeta',
age: 25,
Designation: 'Programmer',
_id: '001',
_rev: '1-23cf3767e32a682c247053b16caecedb' } },
{ id: '002',
key: '002',
value: { rev: '1-d5bcfafbd4d4fae92fd7fc4fdcaa3a79' },
doc:
{ name: 'Zara Ali',
age: 24,
Designation: 'Manager',
_id: '002',
72
PouchDB
_rev: '1-d5bcfafbd4d4fae92fd7fc4fdcaa3a79' } },
{ id: '003',
key: '003',
value: { rev: '1-c4cce025dbd30d21e40882d41842d5a4' },
doc:
{ name: 'Mary',
age: 23,
Designation: 'Admin',
_id: '003',
_rev: '1-c4cce025dbd30d21e40882d41842d5a4' } } ]
73
18. PouchDB – Synchronization PouchDB
You can synchronize the databases stored locally in PouchDB with those that are stored
in CouchDB. In the previous chapter, we have seen how to replicate databases using
PouchDB. There we have used the method PouchDB.replicate(source, destination).
In addition to this, we can also replicate the data, from the local database to the remote
database, and from the remote database to the local database using replicate.to() and
replicate.from()methods as shown below.
Example
Suppose there is a database with the name local_database in PouchDB, and it contains
3 documents, doc1, doc2, and doc3, having contents as shown below.
And there is a database with the name Remote_Database in CouchDB and it contains 2
documents doc1, doc2, having contents as shown below.
74
PouchDB
Save the above code in a file with the name Synchronising_databases.js. Open the
command prompt and execute the JavaScript file using node as shown below.
This synchronizes the two databases remoteDB and localDB, and displays a message on
the console as shown below.
In the same way, if you fetch the contents of the local_database stored in PouchDB
you can get to observe that documents of the database that is stored in CouchDB were
copied here.
[ { id: '001',
75
PouchDB
key: '001',
value: { rev: '1-23cf3767e32a682c247053b16caecedb' },
doc:
{ name: 'Geeta',
age: 25,
Designation: 'Programmer',
_id: '001',
_rev: '1-23cf3767e32a682c247053b16caecedb' } },
{ id: '002',
key: '002',
value: { rev: '1-d5bcfafbd4d4fae92fd7fc4fdcaa3a79' },
doc:
{ name: 'Zara Ali',
age: 24,
Designation: 'Manager',
_id: '002',
_rev: '1-d5bcfafbd4d4fae92fd7fc4fdcaa3a79' } },
{ id: '003',
key: '003',
value: { rev: '1-bf4619471ac346fdde46cfa8fbf3587f' },
doc:
{ name: 'Ram',
age: 26,
Designation: 'Programmer',
_id: '003',
_rev: '1-bf4619471ac346fdde46cfa8fbf3587f' } },
{ id: '004',
key: '004',
value: { rev: '1-29b8f803958c994e3eb37912a45d869c' },
doc:
{ name: 'Robert',
age: 27,
Designation: 'Programmer',
_id: '004',
_rev: '1-29b8f803958c994e3eb37912a45d869c' } },
{ id: '005',
key: '005',
value: { rev: '1-0eb89f71998ffa8430a640fdb081abd2' },
76
PouchDB
doc:
{ name: 'Rahim',
age: 28,
Designation: 'Programmer',
_id: '005',
_rev: '1-0eb89f71998ffa8430a640fdb081abd2' } } ]
You can rewrite the above program using the sync() method provided by PouchDB
instead of the two methods replicate.to() and replicate.from()as shown below.
On executing the above program, it synchronizes the two databases displaying the
following message.
{ push:
{ ok: true,
start_time: Fri Mar 25 2016 15:54:37 GMT+0530 (India Standard Time),
docs_read: 6,
docs_written: 6,
doc_write_failures: 0,
77
PouchDB
errors: [],
last_seq: 10,
status: 'complete',
end_time: Fri Mar 25 2016 15:54:37 GMT+0530 (India Standard Time) },
pull:
{ ok: true,
start_time: Fri Mar 25 2016 15:54:37 GMT+0530 (India Standard Time),
docs_read: 0,
docs_written: 0,
doc_write_failures: 0,
errors: [],
last_seq: 2,
status: 'complete',
end_time: Fri Mar 25 2016 15:54:37 GMT+0530 (India Standard Time) } }
78
19. PouchDB – Miscellaneous PouchDB
In this chapter, we will discuss the concepts like, compaction and retrieval of bulk data
from PouchDB.
Compaction
You can reduce the size of a database by removing the unused data using compact()
method. You can compact a local database as well as remote database using this
method.
79
PouchDB
//Preparing documents
//Inserting Document
db.bulkGet({docs: [
{ id: "001", rev: "1-5dc593eda0e215c806677df1d12d5c47"},
{ id: "002", rev: "1-2bfad8a9e66d2679b99c0cab24bd9cc8"},
{ id: "003", rev: "1-7cff4a5da1f97b077a909ff67bd5b047"} ]}, function(err,
result) {
if (err) {
return console.log(err);
}else {
console.log(result);
}
});
80