Publisher

Category

Price

Versions

Published On

Tags

Couchbase Lite for .NET

Getting Started with Couchbase

You'll probably create a new document when the user creates a persistent data item in your app, such as a reminder, a photograph or a high score. To save this, you'll construct a JSON-compatible representation of the data, then instantiate a new Document and save the data to it.

Next, ask the Database (instantiated when you initialized Couchbase Lite, remember?) for a new document. This doesn't add anything to the database yet; just like the New command in a typical Mac or Windows app, the document won't be stored on disk until you save some data into it. Continuing from the previous example:

You might be wondering which of these lines actually hits the database. The answer is that the Document starts out empty and loads its contents on demand, then caches them in memory; so it's the call to document.Properties that does it. Afterwards, getting properties is as cheap as a dictionary lookup. (For this reason it's best not to keep references to huge numbers of Document objects, or you'll end up storing all their contents in memory. Instead, rely on queries to look up documents as you need them.)

Updating A Document

Updating a document is trivial: You just call PutProperties again.

OK, it's not quite that trivial. Remember the dry theoretical discussion of Multiversion Concurrency Control (MVCC) back in section 2? Here's where it gets real. When you update a document, Couchbase Lite wants to know which revision you updated, so it can stop you if there were any updates in the meantime. (Otherwise, you would wipe out those updates by overwriting them.) I'll get into update-conflict handling in a little bit; for now, just realize that Couchbase Lite wants to see that _rev property in the properties you're putting.

Fortunately this is painlessly accomplished, since the _rev property was already in the dictionary you got from the Document. So all you need to do is modify the properties dictionary and hand back the modified dictionary, which still contains the _rev property, to PutProperties

Alternatively, you can take an easier route and use the Update() method. This works on a similar basis to PutProperties but will retry in the event of a conflict so you don't need to worry about including the _rev item. It will look something like this: