You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose Pagination v5.0.3分页问题:刷新跳404,需两次刷新才正常

Hey there, let’s tackle this frustrating pagination issue you’re hitting with mongoose-pagination v5.0.3 and Node.js 9.3.0. It’s super annoying when things work on first load but break on refresh—let’s walk through the most likely fixes:

1. Fix Your Route Order (The #1 Culprit)

First off, double-check the order of your Express routes. If your 404 wildcard route is defined before your pagination route, Node.js will match the 404 first every time you refresh, which explains the broken behavior.

Correct Route Order:

// Define your pagination route FIRST
app.get("/blogs/page/:page", (req, res) => {
  // Your pagination logic here
});

// THEN define the 404 wildcard route as the last catch-all
app.get("*", function(req, res) {
  res.render("pages/404page");
});

Express matches routes in the order they’re defined, so specific routes always need to come before generic wildcard routes.

2. Validate and Sanitize Pagination Parameters

When you refresh, the page parameter in the URL might be malformed (e.g., a string instead of a number) or out of bounds, causing your pagination query to fail silently and fall through to the 404 route. Add validation to handle this:

app.get("/blogs/page/:page", (req, res) => {
  // Convert page param to a number and validate it
  const page = parseInt(req.params.page, 10);
  
  // Redirect to page 1 if the param is invalid
  if (isNaN(page) || page < 1) {
    return res.redirect("/blogs/page/1");
  }

  // Run your pagination query
  Blog.paginate({}, { page: page, limit: 10 }, (err, result) => {
    if (err) {
      console.error(err);
      return res.status(500).render("pages/error"); // Handle server errors properly
    }

    // If the requested page has no content, redirect to the last valid page
    if (result.docs.length === 0) {
      return res.redirect(`/blogs/page/${result.totalPages || 1}`);
    }

    res.render("blogs", { pagination: result });
  });
});

This ensures invalid or out-of-range page requests don’t trigger a 404.

3. Fix Async/Callback Misalignment

Node.js 9.3.0 supports async/await, but mongoose-pagination v5.0.3 is callback-based. If you’re mixing async functions with callbacks incorrectly, you might be leaving requests hanging, which can lead to unexpected 404s. Stick to consistent handling:

Avoid this mistake:

// ❌ Bad: Async function with no await for the callback
app.get("/blogs/page/:page", async (req, res) => {
  const page = parseInt(req.params.page, 10);
  Blog.paginate({}, { page, limit:10 }, (err, result) => {
    if (err) console.error(err);
    res.render("blogs", { result });
  });
});

Instead, either use pure callbacks (like the example in step 2) or promisify the paginate method if you prefer async/await:

const { promisify } = require("util");
const paginateBlogs = promisify(Blog.paginate.bind(Blog));

app.get("/blogs/page/:page", async (req, res) => {
  try {
    const page = parseInt(req.params.page, 10);
    if (isNaN(page) || page <1) return res.redirect("/blogs/page/1");
    
    const result = await paginateBlogs({}, { page, limit:10 });
    if (result.docs.length ===0) return res.redirect(`/blogs/page/${result.totalPages ||1}`);
    
    res.render("blogs", { pagination: result });
  } catch (err) {
    console.error(err);
    res.status(500).render("pages/error");
  }
});
4. Rule Out Frontend Caching or Route Conflicts

If you’re using client-side routing (e.g., React/Vue), make sure your pagination links are pointing to actual backend routes, not just client-side paths. For example, use <a href="/blogs/page/2"> instead of JS-only navigation that modifies the URL without hitting the backend.

Also, add cache-control headers to prevent the browser from caching broken responses:

res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.render("blogs", { pagination: result });

This ensures every refresh pulls fresh data from the server instead of using cached content.

5. Verify Mongoose-Pagination Setup

Double-check that you’ve properly loaded the pagination plugin into your Blog model:

const mongoose = require("mongoose");
const pagination = require("mongoose-pagination");

const BlogSchema = new mongoose.Schema({
  title: String,
  content: String,
  // Your other fields
});

// ✅ Don't forget this line!
BlogSchema.plugin(pagination);

const Blog = mongoose.model("Blog", BlogSchema);

If the plugin isn’t loaded, the paginate method won’t exist, leading to unhandled errors that can trigger the 404 route.

内容的提问来源于stack exchange,提问作者Alisher Musurmonv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:01:43