6

I need to get a document, change/insert/delete some fields and put it back.

The "put" action requires the current revision of the document, but in nano I cannot find any function which takes a revision as a parameter and inserts the document back into the database.

How can I do this with nano?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
DSblizzard
  • 4,007
  • 7
  • 48
  • 76

1 Answers1

9

Note: This is the general algorithm, it is not specific to any library since nano's insert() method doesn't offer anything automated for updating documents.

Get the document, save the current revision, apply your changes and try to send the document with the saved revision number.

Make sure to handle possible 409 conflict responses which occur when a document was altered meanwhile.

In that case you should refetch the document, save the revision number, reapply your changes and then try to send it again with the new revision.

So here is the algorithm:

  1. Get document
  2. Save the _rev
  3. Apply changes
  4. Try to send updated document with saved _rev
  5. Go to step 1 in case of a 409

Checkout the CouchDB HTTP Document API's PUT section and CouchDB's Replication and Conflicts wiki page for more information on that matter. You may also find How To Update A Document With Nano (The CouchDB Client for Node.js) helpful.

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
  • I know that I need revision. Question is what is function with "revision" argument in nano. Right answer but on another question. – DSblizzard Jul 26 '12 at 07:54
  • 1
    It is the right answer even for your question. Just read [nano's Document API](https://github.com/dscape/nano#document-functions) documentation. There is only an `inser()` method which means that you have to set the proper revision on the document you want to insert. – Octavian Helm Jul 26 '12 at 07:58
  • Can you show the code, please? – DSblizzard Jul 26 '12 at 08:00
  • It is pretty much the exact same code you already have but you just add the `_rev` you got when fetching the document to the updated document you want insert. – Octavian Helm Jul 26 '12 at 08:01
  • Sorry, I realised now, that it's not argument, it's field with value – DSblizzard Jul 26 '12 at 08:06
  • This is a great answer. Further detail can be found in this blog post: [How To Update A Document With Nano (The CouchDB Client for Node.js)](http://writings.nunojob.com/2012/07/How-To-Update-A-Document-With-Nano-The-CouchDB-Client-for-Node.js.html) – dscape Jul 26 '12 at 16:45