When I work with PHP
and MySQL
and I need to select number of rows and then count total (for pagination, for exmaple) I do something like this:
$rows = DB::getRows('
SQL_CALC_FOUND_ROWS
select *
from posts
where mode = "published"
order by `dateCreated`
limit '.$limit.'
');
and then
$totalRows = DB::getOne('
SELECT FOUND_ROWS()
');
Easy and simple.
Recently I started to work on nodejs/mongo project and I wonder what is the cleanest way to achieve the same goal with mongoose.
Now my code looks like this:
var result = {};
var sort = {dateCreated: -1};
var skip = limit * (page - 1);
modelClass.find(function (err, items) {
result.items = items;
modelClass.find().where('mode').equals('published').count(function (err, total) {
result.totalItems = total;
callback([], result);
});
}).where('mode').equals('published').sort(sort).limit(limit).skip(skip);
What I do not Like is that I am repeating myself in .where('mode').equals('published')
.
Is there a better way to do it?
Aucun commentaire:
Enregistrer un commentaire