分页下降顺序

时间:2018-05-11 21:35:40

标签: node.js mongoose

我目前开发了一款博客应用,最近添加了分页功能。我已经检查了几个帖子,并列出了我用来使博客文章作为最新的首页出现在下面的方法。下面是我尝试过的代码和代码。

// 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});
          }
            });
        });
    }
});

我已经尝试了这个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) { ... });

我的帖子有以下架构,其中包括已创建的/日期:

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"
      }
   ]
});

1 个答案:

答案 0 :(得分:0)

请参阅reference。您需要使用列名进行排序。

Blog.find({}).sort('-created')

OR

Blog.find({}).sort({created: -1})