Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to write group by query using Mongoosejs?

How to write group by query using Mongoosejs?

Problem

I'm using nodejs, Mongoose odm, and mongo for a web app and am running into issues trying to run "group by" style query in mongoose:

var results = mymodel.collection.group (
{   
    keyf:
        function(doc)
        {
                var m = doc.date.getMonth();
                var d = doc.date.getDate();
                var y = doc.date.getFullYear();
                return { date: m + "/" + d + "/" + y };
        },
    cond: {},
    reduce: function(doc,prev) { prev.total += doc.value; },
    initial: { total: 0 }
}
);
if(results == null)
{
    console.log("results is null\n");
}

if I run the "mymodel.collection.group" code in mongo shell, it works perfectly. However, in nodejs/mongoose it seems to return a null result even though the mongoose documentation states that direct mongo code could be executed against the native mongo driver.

does anyone have any ideas how to resolve?

Problem courtesy of: iancormac

Solution

I have just managed to do it in Mongoose. To do it you need to create a chained call and in the callback do the reduce.

var foo = function(name, callback){
 Model.where('user', name).
        select('points').
        run(callback);
}

So the above is the map and then reduce is

foo(name, function(errors, docs){ 
                var score = 0; 
                for (var i=0; i 

That works for my needs at the moment

Solution courtesy of: AutomatedTester

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

How to write group by query using Mongoosejs?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×