1

Good day all, can someone suggest me which async function should i use?, in my case, I need an output the 1st member of each group. *** note this is just a example of the flow of my program.

/*  
    Grouplist               groupmember 
    Id | name           id |  name   | group
    1  | group1          1 |  John   |   1
    2  | group2          2 |  James  |   1   
    3  | group3          3 |  Paul   |   3
                         4 |  Angel  |   2
                         5 |  Anne   |   2
                         6 |  Jane   |   3   

    looking for output like this
        id |  name   | group
         1 |  John   |   1
         4 |  Angel  |   2   
         3 |  Paul   |   3  
*/ 
var name = [];
Grouplist.find( function(err, grouplist){

        for(var x=0;x<=grouplist.length-1; x++){
        groupmember.find({id:grouplist[x].id}).limit(1).exec(
        function callBack(err,results){
        if(err) console.log(err);
        name[x] = results.name;
        })
        }    
        })
zxcetera
  • 115
  • 2
  • 14

1 Answers1

3

You can get the result in one query using mongodb aggregate operators:

groupmember.aggregate(
   [
     {
       $group:
         {
           _id: "$group",  //grouping key
           member: { $first: "$$CURRENT" }  //return the first matched document
         }
     },
     {
        $project :   //project the document to top-level
          {     
            _id: "$member._id",
            name: "$member.name",
            group: "$member.group"
          }
    }
   ], 
   function(err, members){
       console.log(members)
   }
)
hassansin
  • 16,918
  • 3
  • 43
  • 49
  • add a `$sort` operator at the beginning of pipeline if you need sorted output. – hassansin Aug 13 '15 at 03:15
  • thanks for the reponse sir, but im getting this error [link](http://i871.photobucket.com/albums/ab275/exaflare07/error_zpsug0gjycg.png) – zxcetera Aug 13 '15 at 03:38
  • It's probably because Salijs wraps the native model class with a higher level class that has no aggregate method. See this answer http://stackoverflow.com/a/27497984/1807881 about how to run aggregate operation on a sailsjs model. – hassansin Aug 13 '15 at 03:47
  • thanks but I can't understand even, i think i need to learn more about monggodb thanks thanks – zxcetera Aug 13 '15 at 05:14