PouchDB
02 / 02

PouchDB: Conflicts, Attachments & Real-Time Updates

PouchDB: Conflicts, Attachments & Real-Time Updates

Handling Conflicts

A document edited offline on two different devices, then synced, can diverge -- PouchDB detects this via the _rev history rather than silently picking a winner. The application needs its own resolution strategy: 'most recent wins' is a common simple default; a collaborative app might merge fields or prompt the user.

Attachments: Binary Data on a Document

// Attaches a photo directly to a journal entry -- syncs along
// with the rest of the document through the same mechanism
db.putAttachment('entry_42', 'photo.jpg', doc._rev, blob, 'image/jpeg')

Custom Queries with Views

// map function emits key-value pairs -- letting a query index by
// something other than _id, like sorting notes by creation date
const mapFn = function (doc) {
  if (doc.type === 'note') emit(doc.createdAt, doc.title)
}

db.query(mapFn, { descending: true }).then((result) => {
  result.rows.forEach((row) => console.log(row.key, row.value))
})

Real-Time Change Notifications

// live: true streams changes as they happen -- no need to
// manually poll and diff the whole database on an interval
db.changes({ live: true, since: 'now', include_docs: true })
  .on('change', (change) => updateUI(change))

Why Local-First Matters Beyond "Fully Offline"

Even in environments where connectivity is usually available, PouchDB's local-first design (read/write locally first, sync in background) keeps the UI responsive during brief connectivity hiccups -- a spotty wifi signal or cellular dead zone -- not just during dramatic fully-offline scenarios.

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

Start free