Bob Dill
Bob Dill

Reputation: 1010

CouchDB View not returning documents when ?key specified

I'm coming to CouchDB from an SQL background and am trying to do the common "SELECT FROM DB where field = someValue". I've created the following design document:

{
   "_id": "_design/views",
   "views": {
       "byRubric": {
           "map": "function(doc) {if(doc.idRubric){emit(doc._id, doc.idRubric);} }"
       }
   }
}

If I query the CouchDB table using the following URL, it correctly returns all 15 documents in the table: http://localhost:5984/rubric_content/_design/views/_view/byRubric

If, however, I try to get those documents in this view which have a particular value in the idRubric field, one which I know is present by, for example, executing the following url, I get 0 documents back when, in fact, 12 of the 15 documents have this specific value in the idRubric field. http://localhost:5984/rubric_content/_design/views/_view/byRubric?key="9bf94452c27908f241ab559d2a0d46c5" (no, it doesn't make any difference if the " marks are replaced by %22). The URL does fail if I leave the quote marks off.

What am I missing? Running this locally for test on OSX 10.12.3 using couchdb - Apache CouchDB 1.6.1

Upvotes: 0

Views: 971

Answers (1)

Alexis Côté
Alexis Côté

Reputation: 3690

Your view is emitting the document with the document with the id as the key.

Instead, you want to emit the the rubricID as the key.

{
   "_id": "_design/views",
   "views": {
       "byRubric": {
           "map": "function(doc) {if(doc.idRubric){emit(doc.idRubric);} }"
       }
   }
}

Then, the query will be the following :

http://localhost:5984/rubric_content/_design/views/_view/byRubric?key="rubric3"

When you use a map, you need to think as if it was a dictionnary. You have a key and a value. You will search for a matching key and get the value.

If you don't emit any value, you can simply use the ?include_docs=true parameter to get the entire document.

Upvotes: 1

Related Questions