Reduce函数异常:无法遍历Map输出值获取最新Issue
Hey there, let's break down what's going on here and fix that Reduce function for you.
The Root Cause
Your problem comes down to not handling the rereduce parameter in your CouchDB Reduce function. CouchDB runs Reduce in stages: when it needs to combine intermediate results from separate chunks of data, it sets rereduce=true, and the values parameter will contain the outputs from previous Reduce calls (not the raw Map output). That's why you're seeing nested arrays and a values.length of 3 instead of 4—two of your records were already processed once, wrapped into a result, and passed into the next Reduce call.
The Correct Reduce Function
To grab the latest record for each Issue, we need to first flatten any intermediate results (when rereduce is true), then find the entry with the most recent date. Here's the working code:
function (keys, values, rereduce) { // Flatten values: handle intermediate reduce results let flatValues = []; if (rereduce) { // When rereduce is true, values are previous reduce outputs (single objects) values.forEach(val => flatValues.push(val)); } else { // Raw Map output values, use as-is flatValues = [...values]; } // Find the record with the latest date let latestRecord = flatValues[0]; flatValues.forEach(record => { if (new Date(record.date) > new Date(latestRecord.date)) { latestRecord = record; } }); return latestRecord; }
One Important Query Detail
Don't forget to add group=true to your view query! Without it, CouchDB will combine all results into a single entry (which is why you saw key: null). Your query should look something like this:GET /your-db/_design/your-design-doc/_view/your-view-name?group=true
This tells CouchDB to run the Reduce separately for each unique Issue ID (your Map output key), so you'll get one latest record per Issue.
内容的提问来源于stack exchange,提问作者Ahmed Yousry

