skip to Main Content

I have created a html page to filter some data in MongoDb and render the data to a display page. And set pagination in the display page. Whenever I choose a new page number, the URL append the page number in the pagination.

Index.js

  let results = await db.collection("bookings").find(whereClause,
    {
      limit: perPage,
      skip: perPage * (Math.max(req.query.page - 1, 0) || 0)
    }
    ).toArray();

  var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

return res.render('search', { bookings: results, pages: pages, perPage: perPage, fullUrl:fullUrl });

Pagination Page:

  <nav aria-label="Page navigation example">
    <ul class="pagination flex-wrap">
      <% for (var i = 1; i <= pages; i++) { %>
        <li class="page-item"></li>
          <a class="page-link" href="<%=fullUrl%>&perPage=<%=perPage%>&page=<%= i %>">
            <%= i %>
          </a>
        </li>
      <% } %>
    </ul>
  </nav>

The problem is every time when I click a new page number in the pagination, it will append the perPage and page parameter into the original link.

http://localhost:3000/search?numTickets=1&name=somename&perPage=6&page=5&perPage=6&page=3

2

Answers


  1. Try to remove the perPage and page parameters from the fullUrl before returning it:

    let results = await db
      .collection('bookings')
      .find(whereClause, {
        limit: perPage,
        skip: perPage * (Math.max(req.query.page - 1, 0) || 0),
      })
      .toArray();
    
    var newUrl = req.protocol + '://' + req.get('host') + req.baseUrl;
    var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    
    const urlSplit = fullUrl.split('?');
    if (urlSplit.length > 1) {
      const queryParams = urlSplit[1]
        .split('&')
        .map((q) => {
          const split = q.split('=');
          if (split.length < 2 || split[0] === 'perPage' || split[0] === 'page')
            return '';
          return q;
        })
        .filter(q => q != '')
        .join('&');
      newUrl += '?' + queryParams;
    }
    
    return res.render('search', {
      bookings: results,
      pages: pages,
      perPage: perPage,
      fullUrl: newUrl,
    });
    
    Login or Signup to reply.
  2. Parse the original URL into an URL instance. Then you can more easily manipulate the searchParams

    const fullUrl = new URL(
      `${req.protocol}://${req.get("host")}${req.originalUrl}`
    );
    fullUrl.searchParams.set("perPage", perPage);
    fullUrl.searchParams.delete("page");
    
    return res.render("search", {
      bookings: results,
      pages,
      fullUrl,
    });
    

    and in your template…

    <% for (var i = 1; i <= pages; i++) { %>
    <li class="page-item">
      <a class="page-link" href="<%=fullUrl%>&amp;page=<%=i%>">
        <%= i %>
      </a>
    </li>
    <% } %>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search