Below is the function I'm utilizing to extract and create issue objects from all documents of type inspection:
function (doc) {
if(doc.doctype === "inspection"){
for(var i=0; i<doc.issues.length; i++) {
emit(doc.issues[i].id, {id: doc.issues[i].id, status: doc.issues[i].status, date: doc.date});
}
}
}
I am using the id property of each issue as the key to filter the results later by issue. This functionality works correctly and yields 4 different states for the same issue with varying dates:
{"total_rows":4,"offset":0,"rows":[
{"id":"31cc62d44e1723f4e39757758101a79a","key":"31cc62d44e1723f4e397577581019612","value":
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-02"}},
{"id":"31cc62d44e1723f4e39757758101f808","key":"31cc62d44e1723f4e397577581019612","value":
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-16"}},
{"id":"31cc62d44e1723f4e39757758102f70e","key":"31cc62d44e1723f4e397577581019612","value":
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-11-01"}},
{"id":"31cc62d44e1723f4e397577581033cab","key":"31cc62d44e1723f4e397577581019612","value":
{"id":"31cc62d44e1723f4e397577581019612","status":"cancelled","date":"2015-12-07"}}
]}
The challenge arises when attempting to run a reduce function to fetch only the latest issue, not being able to iterate through all values. Even though the map function returns 4 rows, the length of the values parameter in the reduce function turns out to be 3 as shown below:
function (keys, values, rereduce) {
return values.length
}
{"rows":[
{"key":null,"value":3}
]}
Furthermore, when trying to display the original values to understand the situation better, it is apparent that two of the values have been grouped together unexpectedly:
{"rows":[
{"key":null,"value":[
[{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-11-01"},
{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-02"}],
[{"id":"31cc62d44e1723f4e397577581019612","status":"cancelled","date":"2015-12-07"}],
[{"id":"31cc62d44e1723f4e397577581019612","status":"pending","date":"2015-09-16"}]]}
]}
This demonstrates a case where the first two objects are combined into one array.
In this perplexing scenario, I seem to believe it's a simple task but I cannot pinpoint what might be amiss...
I attempted iterating through the values parameter to compare the date attribute, however, that did not yield successful results. Similarly, using the following code to recursively search for the id attribute also proved to be unsuccessful:
function (keys, values, rereduce) {
var res = [];
function extractVal(obj) {
if(obj.id) {
res.push(obj.id);
}else {
for(key in obj) {
extractVal(obj[key]);
}
}
}
extractVal(values);
return res;
}