How can I safely create related documents in Couchbase Lite iOS?

For example, I have a transaction in my app that involves many related documents like checking out a cart (with 1 document per product) with a purchase document that references all those product documents.

In this transaction, user may optionally answer a survey/feedback per product if he/she has purchased them before. So that’s 1 document per feedback. I then log these activities in another document so their reference ids are saved in that document.

With all these documents, how do I safely create them? What if during the creation of product documents, an error occurred? Or when I create the feedback documents? How do I handle these errors and ensure my database’s integrity?

You can use Database.inTransaction to group operations that should have all-or-nothing semantics. Returning false from the callback block will abort the transaction.

However, transactions only exist locally. When documents are replicated, they’re copied individually to or from the server, not as part of a transaction. In general, in a distributed system like this you don’t have full consistency across all documents. The only consistency guaranteed is within a single document. So your code needs to be robust against other inconsistencies, i.e. a reference to another document that doesn’t exist yet or has an older revision.

1 Like