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?
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
Discussion
View additional discussion.