【问题标题】:Pagination with MongoDB in Node.js (With Sorting)在 Node.js 中使用 MongoDB 进行分页(带排序)
【发布时间】:2016-02-26 09:44:06
【问题描述】:

使用来自herehere 的建议,我正在尝试通过以下方式实现可扩展、分页、无状态的 REST API:

//Page 1
db.users.find().limit(pageSize);
//Find the id of the last document in this page
last_id = ...

//Page 2
users = db.users.find({'_id'> last_id}).limit(pageSize);
//Update the last id with the id of the last document in this page
last_id = ...

它在大多数情况下都有效,但问题是我必须根据观看次数对视频列表进行排序,然后尝试分页。

// Page 2
videos = db.videos.find({'viewCount'< last_view_count}).sort({viewCount : 'descending'}).limit(pageSize);

这不起作用,因为可能有多个项目具有相同的查看次数,并且当我们这样做时,有些项目会丢失'viewCount'&lt; last_view_count

任何关于如何解决这个问题的想法将不胜感激:)

【问题讨论】:

  • 有没有办法在无状态环境中实现这一点,每个请求都可以访问集群中的任何服务器并单独运行?
  • 无状态请求通常需要会话存储或任何类型的持久性。如果您不使用基于 cookie 的会话,那么您应该在请求中使用令牌。底线是所有工作节点都需要可以访问持久存储。这是高可用性系统中的常见做法。

标签: javascript node.js mongodb mongoose pagination


【解决方案1】:

您可以对一起唯一标识文档的字段组合进行排序和过滤。例如,按{viewcount: 'descending', _id: 'ascending'} 排序,按{viewcount &lt;= last_view_count, _id &gt; last_id} 过滤。

【讨论】:

  • 好答案。只是想知道,有没有办法将其扩展到双向向后/向前分页?前任。在获得第 3 页响应的同时获得第 2 页和第 4 页?
猜你喜欢
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2017-08-03
  • 2011-01-04
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多