blog

  • Home
  • blog
  • Getting Started with PouchDB Client-Side JavaScript Database

Getting Started with PouchDB Client-Side JavaScript Database

Over recent years, client side web applications have gotten more and more sophisticated. Browsers have consistently been providing better JavaScript performance, and are capable of doing more and more things, with rich JavaScript APIs for things like geolocation, and peer-to-peer communication.

The rise of rich web applications also created a need for good client-side storage mechanisms, and that is where JavaScript databases like PouchDB come in.

What is PouchDB?

PouchDB is an open-source JavaScript database inspired by Apache CouchDB that is designed to run well within the browser.

What is a JavaScript database?

In very simple terms, a JavaScript database is a JavaScript object that provides methods (or API) to put, get and search data. In fact, a plain old JavaScript object is the simplest kind of JavaScript database. If you are familiar with Meteor, then you might have heard of Minimongo which is another client side JavaScript database that mimics that MongoDB API.

PouchDB is a JavaScript implementation of CouchDB. Its goal is to emulate the CouchDB API with near-perfect fidelity, while running in the browser or in Node.js.

What makes PouchDB different from databases like Minimongo is that, by default, it is not just in-memory, it uses IndexedDB behind the scenes for its storage. IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs. What this means is that PouchDB data is stored on disk, and will be available even after page refresh (however, data stored by one browser will not be available to other browsers).

Different adapters let you change the underlying data storage layer.

Relation to CouchDB

PouchDB is a JavaScript implementation of CouchDB, and emulates it’s API as closely as possible.

In CouchDB, you’d fetch all the documents using this API call

/db/_all_docs?include_docs=true

In PouchDB, it becomes

db.allDocs({include_docs: true})

PouchDB enables applications to store data locally while offline, then synchronize it with CouchDB when the application is back online.

Now, let’s see how you can use PouchDB in your applications.

Installation

To start using PouchDB you just need to include the PouchDB client library. You can use the standalone build, which makes the PouchDB constructor globally available on the window object

<script src="https://cdn.jsdelivr.net/pouchdb/5.4.5/pouchdb.min.js"></script>

or, if you are using it in Node.js/browserify/webpack environment, you can install it with npm.

$ npm install pouchdb --save

Then in your JavaScript:

var PouchDB = require('pouchdb');

(Fun Fact: npm isntall pouchdb also works!)

Working with PouchDB

Creating a database

Creating a PouchDB database is as simple as calling the PouchDB constructor. Let’s create a database called ‘Movies’.

var movies = new PouchDB('Movies');

After running that, you can see basic information about your database, by using the info method, which returns a Promise.

movies
 .info()
 .then(function (info) {
   console.log(info);
 })

The code above outputs the following:

{"doc_count":0,"update_seq":0,"idb_attachment_format":"binary","db_name":"Movies","auto_compaction":false,"adapter":"idb"}

The adapter field indicates that underneath it’s using IndexedDB.

Working with documents

PouchDB is a NoSQL, document-based database, so there is no rigid schema and you can just insert JSON documents directly. Let’s see how you can insert, update, retrieve or delete documents.

Creating a document

You can create a new document using the put method

// returns a promise
db.put(doc, [docId], [docRev], [options])

The params in square brackets are optional. Each document has an _id field associated with it, which works as a unique identifier.

Create a new doc in the previously created Movies database by running the following code:

movies
  .put({
    _id: 'tdkr',
    title: 'The Dark Knight Rises',
    director: 'Christopher Nolan'
  }).then(function (response) {
    console.log("Success", response)
  }).then(function (err) {
    console.log("Error", err)
  })

The response, in case of success, will be something like:

Success {ok: true, id: "tdkr", rev: "3-f8afdea539618c3e8dceb20ba1659d2b"}

Continue reading %Getting Started with PouchDB Client-Side JavaScript Database%

LEAVE A REPLY