Retrieve just deleted document

Just been restoring deleted data from a couchdb. This is how I solved it after a little help from the good people on couchdb irc.

1) A get request to $db/$id?revs=true&open_revs=all where $db is your database name and $id is the id of the doc you deleted.

2) Clean the response. The result of this request wasn't valid json, strangely, and required cleaning. The following worked for me:

var deletedDoc = JSON.parse(xhReq.responseText.substring(xhReq.responseText.indexOf("{"), xhReq.responseText.lastIndexOf("}") + 1));

The resulting object looks like this:

  {
       "_id":"37b580b03b903da2b50f88587d89c15d",
       "_rev":"2-bf3a2888dfe1ce0facef18720dcf97e2",
       "_deleted":true,
       "_revisions":{
              "start":2,
              "ids":["bf3a2888dfe1ce0facef18720dcf97e2","85f141069731f6bc77c910b0341e599f"]
             }
     }

3) Now we can construct the last revision number, the one before it was deleted. Pull out the second guid in the _revisions.ids array and append it with _revisions.start - 1 and a "-" character. This gives you the rev id of the document just before it was deleted.

var preDeleteRevisionNumber = (deletedDoc._revisions.start - 1) + "-"+ deletedDoc._revisions.ids[1];

4) Now collect the original (predelete data) with a get to $db/$id?rev=$preDeleteRevisionNumber

5) To overwrite the old deleted entry you have to post or put back the document with the correct id and the latest revision number (not the pre delete revision number, but the revision number the document has now it has been deleted).

Hope this helps someone.


Ok, figured it out, if anyone interested:

  1. get deleted history, e.g.:

    curl http://example.iriscouch.com/test/_changes
    
  2. you'll see deleted documents with $id and $rev, put empty document as new version, e.g.:

    curl -X PUT http://example.iriscouch.com/test/$id?rev=$rev -H "Content-Type: application/json" -d {}
    
  3. now you can get all revisions info, e.g:

    curl http://example.iriscouch.com/test/$id?revs_info=true
    
  4. obtain version before deletion, e.g.:

    curl http://example.iriscouch.com/test/$id?rev=$prev_rev
    
  5. put it back to couchdb, e.g.:

    curl -X PUT http://example.iriscouch.com/test/$id?rev=$rev -H \'Content-Type: application/json\' -d \'$data\'
    

Let me know if you have any better way, or script.

Tags:

Couchdb