I would like to paginate my blog with AngularJS / Bootstrap client side and Mongoose / Express server side. Actually I make a call to my rest API which return every blogposts i've got in my DB:
Server side lib/controllers/blogs.js
/**
* List of Blogs
*/
exports.all = function(req, res) {
Blog.find().sort('-created').populate('creator', 'username').exec(function(err, blogs) {
if (err) {
res.json(500, err);
} else {
res.json(blogs);
}
});
};
I would like to just get those which are on the actual page, but I don't really know how to do it as I'm calling GET /api/blogs.
Server side lib/config/routes.js
var blogs = require('../controllers/blogs');
app.get('/api/blogs', auth.ensureAuthenticated, blogs.all);
Maybe someone could help me to do it ? I'm totally new to Node.js.
What you need to do, is paginate your data, meaning that you need to return only the first X items (i.e. blog posts) from your DB, at a time. Something like this:
Blog.find().sort('-created').skip(10).limit(10).populate('creator','username').exec(function(err, blogs) {
if (err) {
res.json(500, err);
} else {
res.json(blogs);
}
});
This will return the posts ranging from #11 - #20.
If your posts are not a lot, you can simply use .skip() and .limit() in your query:
/**
* List of Blogs
*/
exports.all = function(req, res) {
Blog.find().sort('-created').skip(req.body.skip).limit(req.body.limit).populate('creator', 'username').exec(function(err, blogs) {
if (err) {
res.json(500, err);
} else {
res.json(blogs);
}
});
};
The above code is not so good in performance when your collection grows. .skip() counts all documents that you are skipping.
Instead you can use range query like:
/**
* List of Blogs
*/
exports.all = function(req, res) {
Blog.find({_id: {$gt: req.body.lastId}).sort('-created').limit(req.body.limit).populate('creator', 'username').exec(function(err, blogs) {
if (err) {
res.json(500, err);
} else {
res.json(blogs);
}
});
};
The last code is better in performance (even if you have thousands posts). But you only have next and previous page and you can't directly jump into n-th page.