What can I do to share code among views in CouchDB?
Example 1 — utility methods
Jesse Hallett has some good utility methods, including
function dot(attr) {
return function(obj) {
return obj[attr];
}
}
Array.prototype.map = function(func) {
var i, r = [],
for (i = 0; i < this.length; i += 1) {
r[i] = func(this[i]);
}
return r;
};
...
Where can I put this code so every view can access it?
Example 2 — constants
Similarly for constants I use in my application. Where do I put
MyApp = {
A_CONSTANT = "...";
ANOTHER_CONSTANT = "...";
};
Example 3 — filter of a filter:
What if I want a one view that filters by “is this a rich person?”:
function(doc) {
if (doc.type == 'person' && doc.net_worth > 1000000) {
emit(doc.id, doc);
}
}
and another that indexes by last name:
function(doc) {
if (doc.last_name) {
emit(doc.last_name, doc);
}
}
How can I combine them into a “rich people by last name” view?
I sort of want the equivalent of the Ruby
my_array.select { |x| x.person? }.select { |x| x.net_worth > 1,000,000 }.map { |x| [x.last_name, x] }
How can I be DRYer?
The answer lies in couchapp. With couchapp you can embed macros that include common library code into any of the design document sections. It is done before the design document is submitted to the server. What you need to do to do the query you ask about is reverse the keys that are emitted so you can do a range query on the “network”
You don’t want to include the doc you can do that with
include_docs=trueon the query parameters. And you get the doc.id for free as part of the key. Now you can do a range query on networth which would look something like this.