Showing the right result from reduce function CouchDB

48 Views Asked by At

I have 'user' document with array named 'Orders'. Every order has properties like 'title', 'date', 'fee'. I would like to calculate the sum of every Order fee for every user in the database.

This is the map function:

map: function(doc) {
            if (doc.Doc_type && doc.Doc_type === 'user' && doc.Orders) {
                for (var i = 0; i < doc.Orders.length; i++) {
                    emit([doc.Orders[i].Order_date], doc.Orders[i].Fee);
                }
            }
        }

And the reduce function:

reduce: function (keys, values, rereduce){
            var sum = 0;
            for(var i=0,fee;fee=values[i];i++){
                sum+=fee;
            }
            return {
                Transactions: sum,
                Revenue: 10
            };
        }

The result I get is:

{"Transactions":"0[object Object][object Object]","Revenue":10}}
1

There are 1 best solutions below

0
On

For simplicity I don't use your particular data structure but the names should be self-explaining.

Emit the key/value pair :username/:fee (maybe you have to parse it into an integer/float) for every order like you do it in your code (map):

for(every_order) {
  emit(username, fee)
}

You will get 1 or more order-rows for every username in the index. If you request the view with ?key=":username" you will get all order-rows in the result array of the response. Now you could summarize the fees client-side e.g. in the browser or - as you have asked for - do the same server-side with the built-in reduce function

_sum

You will get one row per username with the total amount of order fees as value.