How to write a group on demand using Mongoosejs?

I use nodejs, mongoose odm and mongo for a web application, and I am encountering problems trying to run a group by style request 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 code "mymodel.collection.group" in the mongo shell, it works fine. However, nodejs / mongoose seems to return a null result, although the mongoose documentation states that direct mango code can be run against the mongo native driver.

Does anyone have any ideas how to solve them?

+4
source share
2 answers

I just managed to do it in Mangostas. To do this, you need to create a chain call, and make a reduction in the callback.

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

So, the above is a map, and then abbreviation -

 foo(name, function(errors, docs){ var score = 0; for (var i=0; i < docs.length; i++){ score += docs[i].points; }); 

It works for my needs at the moment.

+1
source

I had a similar problem, and I could do this using the aggregation structure.

mymodel.collection.aggregate( { $match : CONDITION }, { $group : _id : { year : { $year : "$date"}, month : { $month : "$date"}, day : { $dayOfMonth : "$date"} }, count : { $sum : 1 } }, { $project : { date : { year : "$_id.year", month : "$_id.month", day : "$_id.day" } }, { $sort : { "date.year" : 1, "date.month" : 1, "date.day" : 1 } }, function(err, res) { ..callback function..} );

-1
source

Source: https://habr.com/ru/post/1380956/


All Articles