PouchDB
01 / 02

PouchDB Fundamentals: Documents, CRUD & Sync

PouchDB: Documents, CRUD & Sync

PouchDB is an open-source JavaScript database that runs directly in the browser (or Node.js), deliberately designed to be API- and sync-compatible with CouchDB -- enabling genuinely offline-first applications that keep working with no connection, then sync automatically once connectivity returns.

Documents & CRUD

const db = new PouchDB('notes')

// Documents are schema-less JSON with a required _id field
db.put({
  _id: 'note_123',
  title: 'Shopping list',
  content: 'Milk, eggs, bread',
}).then((result) => console.log(result))

// post() auto-generates an _id when the app has no natural one
db.post({ title: 'Untitled note' })

// Fetching a specific document by ID
db.get('note_123').then((doc) => console.log(doc))

// Updating requires the CURRENT _rev -- prevents silently
// overwriting a change made elsewhere since you last fetched it
db.get('note_123').then((doc) => {
  doc.title = 'Updated title'
  return db.put(doc)  // doc._rev already carries the current revision
})

// Deletion creates a tombstone revision, not a silent erase --
// needed so the deletion itself can propagate through sync
db.get('note_123').then((doc) => db.remove(doc))

Listing & Querying

// allDocs() enumerates/paginates, get() fetches one known ID
db.allDocs({ include_docs: true, limit: 20 }).then((result) => {
  result.rows.forEach((row) => console.log(row.doc))
})

Live, Resilient Sync

const remoteDB = new PouchDB('https://my-couchdb-server.com/notes')

// live: true keeps syncing in the background as changes occur on
// either side; retry: true reattempts if the connection drops
db.sync(remoteDB, { live: true, retry: true })
  .on('change', (info) => console.log('sync change:', info))
  .on('error', (err) => console.error('sync error:', err))

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free