Find and count all in Sails.js + Waterline
Asked Answered
L

4

8

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.

Longoria answered 9/6, 2015 at 12:51 Comment(0)
U
1
getLength: function(req, res) {
    Posts.find({}).exec(function(err, items){

        return items.length;
    });
}
Ulbricht answered 9/6, 2015 at 13:22 Comment(2)
Yes, but when doing pagination you usually set some criteria in find method like skip and limit so then items.length is not the total number of items in database.Wrist
You could filter the search query. check out this: sailsjs.org/#!/documentation/concepts/ORM/Querylanguage.htmlUlbricht
P
1

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);
});
Persnickety answered 9/6, 2015 at 14:5 Comment(1)
Yes, but then I need to call Post.find().skip(10).limit(10).exec() { ... } to get posts for specific page and that is two method calls. My questions was is there some method that do both requests and returns specific posts collection and a number of total posts in db. What I want is one method with both informations so I have less coding.Wrist
Z
1

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) {
});
Zenobia answered 25/8, 2016 at 9:56 Comment(0)
R
1

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: []
}

*/
Rood answered 21/4, 2017 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.