Keeping Local Documents Local in a CouchDB-Style Replication Job

For when you replicate data, but need to leave a bit of config behind

Glynn Bird
Feb 20, 2018 · 3 min read
  • IBM Cloudant is a hosted version of CouchDB running on IBM’s cloud
  • PouchDB can be installed in many flavours but is commonly used as an in-browser database, to store client-side data with or without network connectivity
We can replicate all the sand (data), but ensure our lone flamingo stays put (local doc). Photo by Jerry Kiesewetter on Unsplash.

What are CouchDB local documents?

CouchDB local documents are JSON documents whose _id value starts with _local/:

{
"_id": "_local/config",
"code": "red",
"defcon": 2,
"timestamp": "2018-02-10"
}

What are local CouchDB documents used for?

If you are replicating data between two members of the CouchDB family (e.g., between your PouchDB-powered web app and hosted Cloudant), you may need to store some configuration on the client side that is:

  • not counted in queries, views or aggregations

CRUD operations for CouchDB local documents

Local documents are created in a similar way to normal JSON documents by using an HTTP POST:

URL="https://username:password@host.cloudant.com/mydatabase"
HEAD="Content-type: application/json"
DOC='{"_id":"_local/config","code":"red"}'
curl -X POST -H "$HEAD" -d "$DOC" "$URL"
# {"ok":true,"id":"_local/config","rev":"0-1"}
# note that the document _id is now in the URL
URL="https://username:password@host.cloudant.com/mydatabase/_local/config"
HEAD="Content-type: application/json"
DOC='{"code":"red"}'
curl -X PUT -H "$HEAD" -d "$DOC" "$URL"
# {"ok":true,"id":"_local/config","rev":"0-1"}
var doc = {"_id":"_local/config","code":"red"};
db.insert(doc).then(...);
DOC='{"code":"orange"}'
curl -X PUT -H "$HEAD" -d "$DOC" "$URL"
curl -X DELETE "https://username:password@host.cloudant.com/mydatabase/_local/config"
# {"ok":true,"id":"_local/config","rev":"0-0"}

IBM CODAIT

Things we made with data at IBM’s Center for Open Source Data and AI Technologies.

Glynn Bird

Written by

Developer @ IBM. https://glynnbird.com

IBM CODAIT

Things we made with data at IBM’s Center for Open Source Data and AI Technologies.