Usage Overview

Douglas Tarr edited this page May 15, 2017 · 12 revisions

Connecting

    require 'couchrest'
    @db = CouchRest.database("http://127.0.0.1:5984/couchrest-test")

CouchRest.database! creates the database if it doesn't already exist:

    @db = CouchRest.database!("http://127.0.0.1:5984/couchrest-test")

If you require authentication, include the credentials in the URL as follows:

    @db = CouchRest.database("http://user:password@127.0.0.1:5984/couchrest-test")

Creating, Saving, and Fetching Documents

    # create
    response = @db.save_doc({:key => 'value', 'another key' => 'another value'})
    # => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd5e5de2", "rev"=>"1-cbb61d1f90f7c01b273737702265b6c8"}
    
    # fetch by id
    doc = @db.get(response['id'])
    # => #<CouchRest::Document _id: "e0d70033da0fad3707fed320bd5e5de2", _rev: "1-cbb61d1f90f7c01b273737702265b6c8", key: "value", another key: "another value">
    
    # update
    doc["boogie"] = true
    @db.save_doc(doc)
    # => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd5e5de2", "rev"=>"2-3b067cc9f01fdf25814445088403382c"}
    
    doc["_rev"]
    # => "2-3b067cc9f01fdf25814445088403382c" <- notice it modified the doc _rev

Attachments

Saving / Fetching Attachments

    contents = "<html><body>If you're happy and you know it, clap your hands.</body></html>"
    @db.put_attachment(doc, "happy.html", contents, :content_type => "text/html")
    # => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd7e0770", "rev"=>"2-20635570c75e8b20f7a73fd1538f318d"}
    
    # NOTE: The document is not updated automatically with the attachment information
    pp doc.to_hash
    # {"_id"=>"e0d70033da0fad3707fed320bd7e0770",
    #  "_rev"=>"1-cbb61d1f90f7c01b273737702265b6c8",
    #  "key"=>"value",
    #  "another key"=>"another value"}
    
    # If you try to fetch the attachment without getting the new state of the document, you will fail
    
    @db.fetch_attachment(doc, "happy.html")
    # => RestClient::ResourceNotFound: 404 Resource Not Found: {"error":"not_found","reason":"Document is missing attachment"}
    
    doc = @db.get(doc["_id"])
    
    pp doc.to_hash
    # {"_id"=>"e0d70033da0fad3707fed320bd7e0770",
    #  "_rev"=>"2-20635570c75e8b20f7a73fd1538f318d",
    #  "key"=>"value",
    #  "another key"=>"another value",
    #  "_attachments"=>
    #   {"happy.html"=>
    #     {"content_type"=>"text/html",
    #      "revpos"=>2,
    #      "digest"=>"md5-q3MreM1aJgfSLHGrJLdg4g==",
    #      "length"=>75,
    #      "stub"=>true}}}
    
    @db.fetch_attachment(doc, "happy.html")
    => "<html><body>If you're happy and you know it, clap your hands.</body></html>"

Deleting attachments

Option 1: Simply remove the metadata from the doc and save

    doc["_attachments"].delete("happy.html") # note, this is just using Hash#delete
    # => {"content_type"=>"text/html", "revpos"=>4, "digest"=>"md5-q3MreM1aJgfSLHGrJLdg4g==", "length"=>75, "stub"=>true}
    
    @db.save_doc(doc)
    # => {"content_type"=>"text/html", "revpos"=>4, "digest"=>"md5-q3MreM1aJgfSLHGrJLdg4g==", "length"=>75, "stub"=>true}
    
    pp doc.to_hash
    # {"_id"=>"e0d70033da0fad3707fed320bd7dfbac",
    #  "_rev"=>"3-89acbafa837098c131e6ac04026b4a1b",
    #  "key"=>"value",
    #  "another key"=>"another value",
    #  "_attachments"=>{}}

Option 2: Use the delete_attachment method

    @db.delete_attachment(doc, "happy.html")
    # => {"ok"=>true, "id"=>"e0d70033da0fad3707fed320bd7df13c", "rev"=>"3-d81116a00196640df650e77c42459969"}

Manipulating a CouchRest::Document Helper Methods

#to_json

    doc.to_json
    # => "{\"_id\":\"e0d70033da0fad3707fed320bd5e5de2\",\"_rev\":\"1-cbb61d1f90f7c01b273737702265b6c8\",\"key\":\"value\",\"another key\":\"another value\"}"

#to_hash

    pp doc.to_hash
    # {"_id"=>"e0d70033da0fad3707fed320bd5e5de2",
    #  "_rev"=>"1-cbb61d1f90f7c01b273737702265b6c8",
    #  "key"=>"value",
    #  "another key"=>"another value"}

#save

    doc["_rev"]
    # => "1-cbb61d1f90f7c01b273737702265b6c8"
    
    doc["another key"] = "boogie"
    doc.save
    # => true
    
    # The _rev is automatically updated
    doc["_rev"]
    # => "2-3b067cc9f01fdf25814445088403382c"

Bulk Save:

    pp @db.bulk_save([
      {"wild" => "and random"},
      {"mild" => "yet local"},
      {"another" => ["set","of","keys"]}
    ])
    # [{"id"=>"e0d70033da0fad3707fed320bd5e5b5e",
    #   "rev"=>"1-ba668e67fa88ff8c39bb26f0023f5006"},
    #  {"id"=>"e0d70033da0fad3707fed320bd5e51fa",
    #   "rev"=>"1-8b763b91759b1db7cd9683eb5290b6a9"},
    #  {"id"=>"e0d70033da0fad3707fed320bd5e4a72",
    #   "rev"=>"1-9357f0bc3307f4e1391b82b263be637c"}]

Creating and Querying Views:

    @db.save_doc({
      "_id" => "_design/first", 
      :views => {
        :test => {
          :map => "function(doc){for(var w in doc){ if(!w.match(/^_/))emit(w,doc[w])}}"
          }
        }
      })
    puts @db.view('first/test')['rows'].inspect 

Replication:

    @db.replicate_to(@other_db)

Note: You must be authenticated as an admin to create design documents.

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.