Find and count all in Sails.js + Waterline

4.7k views Asked by At

Is there a way to do select query and count_all query via single method? For pagination purposes we need to know total number of items so we can calculate and show number of pages.

4

There are 4 answers

2
Matan Gubkin On
getLength: function(req, res) {
    Posts.find({}).exec(function(err, items){

        return items.length;
    });
}
1
Yann Bertrand On

Check out Sails.Js - How I do pagination in sails.Js for pagination in Waterline.

To get the total number of items, you can use:

Post.count().exec(function (err, nbOfInstances) {
    if(err) return res.negociate(err);

    return res.ok(nbOfInstances);
});
0
rash111 On

First you query and get data after that you delete limit, skip parameters and get count

delete query._criteria.limit;
delete query._criteria.skip;
Model.count(query._criteria).exec(function countCB(error, count) {
});
0
Raza Ahmed On

I also couldn't find any built-in method to do that in one request so I do it like this:

let queryParams = {},
    pageNo = 1,
    perPage = 10;
Post.count(queryParams)
    .then(_count=>{        
        return {posts_count: _count, 
               posts: Post.find(queryParams).paginate({page: pageNo, limit: perPage})};
     })
     .then(res.ok)
     .catch(err=>res.negotiate(err.message));

OUTPUT:

/*
{
   posts_count: 0,
   posts: []
}

*/