flatiron/resourceful — pull request #63 by distracteddev (2012-04-15 07:40:44+00:00)
Title: Aggregate CouchDB Views Do Not Work

Currently, it seems that Resourceful is set up to automatically instantiate a Resource from the .value/.doc attribute that is passed back within each row of a CouchDB View's response.

However, this does not work for view functions that are "aggregates". This means that they compute some values based on all the rows a regular query would return. A simple and common example is the SUM() query, which is available in SQL/CouchDB alike. Below is a more detailed explanation of the bug.

* The Resourceful Model with the custom filter defined
https://gist.github.com/2389967
* The server route that calls the filter on the defined Resource.
https://gist.github.com/2389986

The response from the couchDB view (This is the correct response):

{
rows: [
{
key: "Test",
value: 2
}
]
}
// Incase it helps, what the MapReduce function is doing in this case is
// returning an array of distinct tags as the keys, and their frequency as values. This is a standard view and is ripped
//right out of the couchDB guide.

couchdb/index.js [Line 140](https://github.com/flatiron/resourceful/blob/master/lib/resourceful/engines/couchdb/index.js#L141) - In Couchdb.prototype.view() - Here, the res object is correctly populated with the rows object from the couchDB resonse. However, it strips out only the doc/value attributes from the rows. This suggests that this function was only designed to return information on the values, and never the keys. This is what confuses me.

The r.value the above function returns is 2, which is then passed into the callback as an array defined on line 110/111 of [resource.js](https://github.com/flatiron/resourceful/blob/master/lib/resourceful/resource.js#L110). The result var that is passed to this callback is passed as an array (see below). Thus, the code block at line 126 is executed and the result var is passed into the map function at line 128 that subsequently seems to instantiate resourceful objects out of the result.

There are two problems here.

1. The ._request function is ever only given the key's of a couchDB view back. (The key was stripped out in the function listed above).
2. CouchDB views can return more than just filtered lists of document objects. Why are we automatically trying to instantiate the value/doc attributes of the returned response array - rows (see the above response).

The array that is passed into the callback defined within Resource._request Line 110.

result: [2]