How calculate max value of many document?

18 views
Skip to first unread message

Marco Solci

unread,
Jun 26, 2016, 5:59:12 PM6/26/16
to PouchDB
Hi
I want calculate max value of 'number' field of many documents so i created this function:
getMaxOrder3() {
        var highest;
        if (!highest) {
            this._db.allDocs({include_docs: true, descending: false}, function (err, doc) {
                doc.rows.forEach(function (row) {
                    if (highest == undefined || row.doc.Number > highest) 
                        highest = row.doc.Number;  
                });
                console.log('##---##'+highest); 
                return highest;
            });
        
        } else {
            return new Promise((resolve, reject) => resolve(highest));
        }
    } 

when i call the function in this way :


this.orderService.getMaxOrder3().then(data => this.order.Number = data);
            console.log("###"+this.order.Number);

the console show me 2 result:
###undefined
##---##9


where am I doing it wrong?

the function calculate correctly the maximum but when try to write it it's undefined.

thanks





Nolan Lawson

unread,
Jul 14, 2016, 2:16:25 PM7/14/16
to PouchDB
Hi, it looks like you forgot to put a "return" in your code, so it should be "return  this._db.allDocs..." . Since you forgot to "return", the Promise resolves to undefined.

You may want to read this blog post on Promises; I've been told it's helped people make sense of them: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

Cheers,
Nolan
Reply all
Reply to author
Forward
0 new messages