hbwtgq
Last Updated: February 25, 2016
·
1.515K
· runexec
81609937c20aeab3598aea56f1f4f022

CouchDB - The Death of Queries & Javscript

This quick tutorial will show you one of many alternatives to the well missed sql query. CouchDB has many different ways of making filters and views, but this one is aimed just for your understanding.

My database is called Coderwall, and we'll get the following JavaScript to act as a query alternative for our view called pro-or-not. This will show us if the tip is from a professional.

function(doc) {
  if(doc.type == "protip" && doc.public) {
    emit("Protip "+doc._id, doc);
  }else{ emit("Not Pro Tip", doc); }
}

Let's make sure it works
http://localhost:5984/coderwall/_design/protips

{    

    "_id": "_design/protips",    
    "_rev": "1-ff083d518ab7d3bcda7b111cb3c62f10",    
    "language": "javascript",    
    "views": {    
        "pro-or-not": {    
            "map": "function(doc) {\n if(doc.type == \"protip\" && doc.public) {\n \temit(\"Protip \"+doc._id, doc);\n }else{ emit(\"Not Pro Tip\", doc); }\n}"    
        }    
    }    

}

Let's get our view! Notice the value of 'key'
http://localhost:5984/coderwall/_design/protips/_view/pro-or-not

database - coderwall    
_design - protips    
_view - pro-or-not    

{"total_rows":2,    
"offset":0,    
"rows":[    
{"id":"e9006a913083f861a4e8de607d001355",    
"key":"Not Pro Tip",    
"value":{"_id":"e9006a913083f861a4e8de607d001355",    
"_rev":"2-4d751e64391610984a95f268ceaef462",    
"some-doc":"testing it out"}},    

{"id":"e9006a913083f861a4e8de607d000fbd",    
"key":"Protip e9006a913083f861a4e8de607d000fbd",    
"value":{"_id":"e9006a913083f861a4e8de607d000fbd",    
"_rev":"3-036a650bd59267418e67e163b0a2deac",    
"type":"protip",    
"public":true,    
"title":"Ryan Kelker Mastering CouchDB"}}    
]}    

endorse

Say Thanks
Respond