代码之家  ›  专栏  ›  技术社区  ›  JS Bach

分页降序

  •  1
  • JS Bach  · 技术社区  · 7 年前

    我目前开发了一个博客应用程序,最近添加了分页功能。我检查了几篇文章,并列出了下面我用来让博客文章作为最新的第一个出现在分页中的方法。下面是我的代码和我尝试过的代码。

    // 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 回复  |  直到 7 年前
        1
  •  0
  •   Vasan    7 年前

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

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

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