Basic CRUD with CouchDB/PouchDB

In my previous post I discussed the basics of setting up CouchDB and PouchDB, in this article I'd like to walk you through some common operations we perform on any database: CRUD (Create-Read-Update-Delete) with CouchDB. I'd also add some SQL reference if you're coming from an SQL background.

Given that we already have our PouchDB database ready,

import PouchDB from 'pouchdb'

const db = PouchDB('my-offline-db')

Creating a Record

To create a database record, PouchDB gives us a ready to use interface with self-descriptive methods. Imagine we want to store peoples information based on their twitter handle, we could start by creating a JSON document and calling a post method to create.

const amustapha = {
   name: "Abdulhakeem",
   email: "",
   country: "NG",
   twitter: ""

The snippet above is like writing the following in SQL

INSERT INTO profile (name, email, country, twitter) 
VALUE ('Abdulhakeem', ;', 'NG', '')

When the post function is called, our document is automatically assigned an id, unlike SQL which is often auto-incremented, this is a UUID containing up to 32 characters, and the function also returns a promise.

Reading a Record

To read a database record, we also would refer to the packed in pouchdb helper function get. To run this function, we'll need to pass the id of an existing document.

db.get("unique-doc-id").then(doc => {
/* you can perform any operation on the document returned. */

The snippet above is like writing the following in SQL

SELECT * FROM profile WHERE id = 'unique-doc-id'

Updating a Record

Once we have read a record from the database, we could modify and save that record. For example, imagine a user changing their email. A helper method for this is put

db.get("unique-doc-id").then(doc => { = ""

The snippet above is like writing the following in SQL

UPDATE profile SET email='' WHERE id = 'unique-doc-id'

Delete a Record

To delete a database record, simply use the remove function


Hope you found this interesting, I'll be writing other articles to explore CouchDB queries in-depth and some really interesting plugins that would make life a lot easier for you. If you found it interesting, like it and share with friends.