Reputation: 1330
I build rest api with sails.js. I want implement pagination in my angularjs frontend. To do this I should get a list of items along with the total count of items (to calculate pages count), that meet the criteria.
Unfortunately sails.js returns only data list without total records count.
I expect that the server response will look like this:
{
data: [...], // collection data
count: 193 // records count, that meet the criteria of the request.
}
How can I implement this?
Upvotes: 0
Views: 228
Reputation: 5979
I implimented a set of blueprints that will return a count in ether the header or the body
https://github.com/randallmeeker/SailsBluePrintActions/tree/master/pagination
here is an example
var query = Model.find()
.where( actionUtil.parseCriteria(req) )
.limit( actionUtil.parseLimit(req) )
.skip( actionUtil.parseSkip(req) )
.sort( actionUtil.parseSort(req) );
var metaInfo,
criteria = actionUtil.parseCriteria(req),
skip = actionUtil.parseSkip(req),
limit = actionUtil.parseLimit(req);
Model.count(criteria)
.exec(function(err, total){
if (err) return res.serverError(err);
metaInfo = {
start : skip,
end : skip + limit,
limit : limit,
total : total,
criteria: criteria
};
res.ok({info: metaInfo, items: matchingRecords});
});
Upvotes: 0
Reputation: 830
you can use async.auto
async.auto(
count: functuon(callback){
Model.count(...).exec(callback);
},
data: function(callback){
Model.find(...).exec(callback);
}
},function(err,results){
console.log(results.count);
console.log(results.data);
});
Upvotes: 1
Reputation: 1348
You can use Model.count
to count all data that meet the criteria.
Example:
// very important here to use the same `criteria` for `find` and `count`
var criteria = {foo: 'bar'};
Model.find(criteria).exec(function (err, found) {
Model.count(criteria).exec(function (error, count) {
console.log({ data: found, count: count });
});
});
Upvotes: 0