I have currently developed a blog app and recently add a pagination function. I have checked several posts and have listed the methods below that I have used to get the blog posts to appear in the pagination as newest first. Below is my code and code that I have tried.
// INDEX ROUTE
router.get("/blogs", function (req, res) {
var perPage = 10;
var pageQuery = parseInt(req.query.page);
var pageNumber = pageQuery ? pageQuery : 1;
var noMatch = null;
if (req.query.search) {
const regex = new RegExp(escapeRegex(req.query.search), 'gi');
Blog.find({name: regex}).skip((perPage * pageNumber) - perPage).limit(perPage).sort('-date').exec(function (err, blogs) {
Blog.count({name: regex}).exec(function (err, count) {
if (err) {
console.log("ERROR!");
} else {
if (blogs.length < 1) {
noMatch = "No blogs match that query, please try again";
}
res.render("blogs/index", {blogs: blogs, current: pageNumber, pages: Math.ceil(count / perPage), currentUser: req.user, noMatch: noMatch, search: req.query.search});
}
});
});
} else {
Blog.find({}).skip((perPage * pageNumber) - perPage).limit(perPage).exec(function (err, blogs) {
Blog.count().exec(function (err, count) {
if (err) {
console.log("ERROR!");
} else {
res.render("blogs/index", {blogs: blogs, current: pageNumber, pages: Math.ceil(count / perPage), currentUser: req.user, noMatch: noMatch, search: false});
}
});
});
}
});
I have tried all of these code from this post
Blog.find({}).sort('-date').exec(function(err, docs) { ... });
Blog.find({}).sort({date: -1}).exec(function(err, docs) { ... });
Blog.find({}).sort({date: 'desc'}).exec(function(err, docs) { ... });
Blog.find({}).sort({date: 'descending'}).exec(function(err, docs) { ... });
Blog.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Blog.find({}, null, {sort: '-date'}, function(err, docs) { ... });
Blog.find({}, null, {sort: {date: -1}}, function(err, docs) { ... });
My post have the following schema which include the created/dates:
var BlogSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
location: String,
lat: Number,
lng: Number,
created:
{type: Date, default: Date.now},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});