Search code examples
node.jssails.jsasync.jssails-mongo

How to Looping inside Model.find Sailsjs


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;
        })
        }    
        })

Solution

  • 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)
       }
    )