简体   繁体   English

如何在nodejs + postgresql中实现分页

[英]How to implement pagination in nodejs + postgresql

I am novice in Node.js.我是 Node.js 的新手。 I want to implement pagination in my Api writing in Node.js using express as a framework and Postgresql as database.我想在 Node.js 中使用 express 作为框架和 Postgresql 作为数据库在我的 Api 编写中实现分页。 I want to get the data in form of pagination.我想以分页的形式获取数据。

Thanks in advance.提前致谢。

You can use LIMIT and OFFSET in order to get chunks of data from the database.您可以使用LIMIT 和 OFFSET从数据库中获取数据块。 You need 2 variables to do the pagination, page and itemsPerPage.您需要 2 个变量来进行分页,page 和 itemsPerPage。 You'd get the page variable from the route itself, for example /api/items/:page, and for the itemsPerPage, you can make it default 20 items for example, but allow the clients to specify it through a query ?items=50 or the request body or a header or however you want.您将从路由本身获取页面变量,例如 /api/items/:page,对于 itemsPerPage,您可以将其设为默认的 20 个项目,例如,但允许客户端通过查询 ?items= 指定它50 或请求正文或标题或您想要的任何内容。 Then when you have both variables you can perform the query on the database, like:然后,当您拥有这两个变量时,您可以对数据库执行查询,例如:

SELECT *
    FROM items
    LIMIT {itemsPerPage} OFFSET {(page - 1) * itemsPerPage}

LIMIT means retrieve me X number of items, OFFSET means skip Y items. LIMIT 表示检索 X 个项目,OFFSET 表示跳过 Y 个项目。 Both of them combined would be: "skip Y items and get me the next X items".它们的组合将是:“跳过 Y 项并为我获取下 X 项”。 Page - 1 means if you're on the 1st page we don't want to skip any items, but retrieve the first X items. Page - 1 表示如果您在第一页,我们不想跳过任何项目,而是检索前 X 个项目。 This is valid when the page number is >= 1.这在页码 >= 1 时有效。

You can use indexes on columns used for sorting in pagination.您可以在用于分页排序的列上使用索引。 Instead of limit & offset you can use where condition on column values (unique values) for efficiency.您可以在列值(唯一值)上使用 where 条件来提高效率,而不是限制和偏移。 I have created a post regarding this https://medium.com/@shikhar01.cse14/pagination-with-postgresql-18e0b89e0b1c我已经创建了一个关于这个https://medium.com/@shikhar01.cse14/pagination-with-postgresql-18e0b89e0b1c的帖子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM