Reputation: 508
I am using nodejs+express+mongodb. I am working on api. I want to do the pagination in nodejs+express. Note: there is mongoose-pagination option but I am not using mongoose. I am using direct mongodb only.
Please tel me how can I do the pagination in nodejs+express. I got this link express-paginate
But I could not work on it. I dont know How can I implement it in my API.
Here is JSON data. In this steps arrays listing more than 10 so I want to do pagination for this.
Here is my API. Here inside steps for loop, I added given(in the above github link) pagination code
const get = (req, res, next) => {
applogger.verbose(`retrieving asdsa with id ${req.params.asd}`);
asd.findOneById(req.params.asd)
.then(function(resp) {
for (var i = 0; i < resp.steps.length; i++) {
if (resp.asd[i].image == null) {
resp.asd[i].image = imgurl;
}
asd.paginate({}, { page: req.query.page, limit: req.query.limit }, function(err, users) {
if (err) return next(err);
res.format({
json: function() {
res.json('users', {
users: users.docs,
pageCount: users.pages,
itemCount: users.limit,
pages: paginate.getArrayPages(req)(3, users.pages, req.query.page)
});
},
json: function() {
// inspired by Stripe's API response for list objects
res.json({
object: 'list',
has_more: paginate.hasNextPages(req)(users.pages),
data: users.docs
});
}
});
});
}
if (resp.asd == null) {
resp.asd = imgurl;
}
res.json(resp);
}, function(err) {
res.send(err);
});
};
Upvotes: 2
Views: 6988
Reputation: 4678
Use your mongo aggregation / find, etc... and just apply the skip and limit operator.
if you want to display X result by page and if you are the page number N (starting from 0)
MyCollection.find([
...
])
.skip(X * N)
.limit(X)
.exec(function(err, result){
///
Tourtle.find({})
.skip(req.skip)
.limit(req.query.limit)
.exec(function(err, users) {
if(err) .... else .....
});
Upvotes: 8
Reputation: 611
In your client you need to do a pagination like:
<ul class="pagination">
<li><a href="/yourRoute/1">1</a></li>
<li><a href="/yourRoute/2">2</a></li>
</ul>
and your back-end be like:
const getTourtle = (req, res, next) => {
var page = req.params.id;
var minPage = 10 * (page - 1);
var maxPage = minPage + 10;
db.collection.find({
//do your query
}).min({_id:min_page}).max({_id:max_page});
res.json(resp); // send response to client
}
Upvotes: 3