Updating local document always fails (iOS Swift)


For some reason I just can not update a local document.

I can create - just not update.

If someone can point out the school boy error that I’m making - I’d be appreciative.

Here’s my code.

  let properties: [String : AnyObject] = [
    "name" : stringValue1,
    "description" : stringValue2

  // Fetch the target document
  let targetDoc = couchbasedatabase.documentWithID(targetdocumentid)
  if let td = targetDoc {

do {
  try td.putProperties(properties)
} catch let error as NSError {
  print("Couldn't update item - \(error)")

The error message I get is:

Couldn't save new item - Error Domain=CBLHTTP Code=409 "conflict" UserInfo={NSLocalizedFailureReason=conflict, NSLocalizedDescription=conflict}


I figure it out - details of how below. I’ll answer so that if anyone else has the same problem the answer might help them.

Basically I switched form using putProperties to using the Update method.

  if let td = targetDoc {
    do {
      try td.update({ (newRev) -> Bool in
        newRev["name"] = stringValue1
        newRev["description"] = stringValue2
        return true
    } catch let error as NSError {
      print("Couldn't save new item - \(error)")


You’ve run into MVCC. To update an existing document, the properties have to contain a _rev field with the document’s current revision ID (the same value it has when you read the document.)

What this means is you can’t just make up a new dictionary and shove it into the document. You need to get the document first, get the properties, incorporate your changes into that dictionary (or at least copy the _rev value from the existing properties into your dictionary), and then put those updated properties back.

The update method is basically a structured way of enforcing that. It also handles the unlikely-but-possible race condition where another thread (e.g. the replicator) updates the doc in between you reading it and writing it back; in that case you’ll get a conflict error and will need to retry. update will retry as often as necessary.


Ah. Right. That makes sense. Thank you for clarifying.

Is there a way I can contribute to updating the documentation? This is really not clear in the GUIDE docs.


The process to contribute to docs is very simple, there’s an Edit on GitHub button on most pages (eventually it will be all pages) that opens the backing markdown file on GitHub. You can then make changes using the GitHub markdown editor and submit a PR or clone the repo if you wish.

The section on updating the document is here http://developer.couchbase.com/documentation/mobile/1.3/develop/guides/couchbase-lite/native-api/document/index.html#updating-documents and the Edit on GitHub button is at the top of the page.



Thanks @jamiltz - I’ll check it out.