9

I am using Waterline ORM for sails.js. limit and sort are not working when you use groupby, but are working fine when you dont do any grouping .

For example

Model.find({
    groupBy:['term'],
    sum:['count'],
    limit:20,
    sort :'count DESC'}).exec(function(error,response){
        if(error) res.json(error);
        res.json(response);
    });
will-hart
  • 3,742
  • 2
  • 38
  • 48
sanath_p
  • 2,198
  • 2
  • 26
  • 22

4 Answers4

10

Use

Model.find()  
 .groupBy('term') 
 .sum('count')  
 .limit(20)
 .sort({count: 'desc'}) 
 .exec(function (err, data){
 //Your code here..
});
Mahammad Adil Azeem
  • 9,112
  • 13
  • 57
  • 84
  • Use `sort` before `groupBy`.. May be this would work.. I hope the above mentioned method is not giving any errors..? – Mahammad Adil Azeem Jul 03 '14 at 15:00
  • tried that one too . Your method is not giving any errors its just displaying all the results . – sanath_p Jul 03 '14 at 15:08
  • That means you are not applying the right filters.. Can you please update your question with your model and Controller files.. i.e `api/models/Foo.js` and `api/controller/whateverController.js` – Mahammad Adil Azeem Jul 03 '14 at 16:17
  • Try replacing 'asc'/'desc' with 1/-1, thus: .sort({count: -1}). – Karma Jun 28 '15 at 14:32
  • is there like toSql method in sails to see our query ? – Faris Rayhan Nov 20 '16 at 06:01
  • "The `groupBy` clause is no longer supported in Sails/Waterline. the usage has changed. Now, to run aggregate queries using the `groupBy` operator, use a native query instead." Sailsjs debugger said – Wajih Nov 03 '18 at 06:44
  • In v1+ groupBy is not supported See official document https://sailsjs.com/documentation/upgrading/to-v-1-0#changes-to-waterline-criteria-usage – Gopal Kohli Jan 10 '23 at 06:51
0

Example override toJSON

    // Your Model
    module.exports = {
        attributes: {
            // some attributes here
            name: 'string',
            email: 'string',
            password: 'string',

            // Override .toJSON instance method
            toJSON: function() {
                var obj = this.toObject();
                delete obj.password;
                return obj;
           }
        }
    };
Ashish Gupta
  • 1,153
  • 12
  • 14
0

Use this :

  Model.find()  
   .sort({count: 'desc'}) 
   .groupBy('term') 
   .exec(function (err, data){
   //Your code here..
  });
Ashish Gupta
  • 1,153
  • 12
  • 14
0

In sails-mongo, for sorting ASC and DESC we can use same like mongo, For an example, if you want to fetch count in DESC order then the query is like,

Model.find({
 sort: {
    count: 0(Note:- Here 0 for DESC and 1 for ASC)
  }
})

Hope it will work for you.

Akib Deraiya
  • 89
  • 2
  • 9