如何在 Node.js 中使用 Mongoose 进行分页? [英] How to paginate with Mongoose in Node.js?

查看:61
本文介绍了如何在 Node.js 中使用 Mongoose 进行分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Node.js 和 mongoose 编写一个 web 应用程序.如何对从 .find() 调用中获得的结果进行分页?我想要一个类似于 SQL 中的 "LIMIT 50,100" 的功能.

I am writing a webapp with Node.js and mongoose. How can I paginate the results I get from a .find() call? I would like a functionality comparable to "LIMIT 50,100" in SQL.

推荐答案

我对这个问题的公认答案感到非常失望.这不会扩展.如果你阅读了 cursor.skip( ) 上的细则:

I'm am very disappointed by the accepted answers in this question. This will not scale. If you read the fine print on cursor.skip( ):

cursor.skip() 方法通常开销很大,因为它需要服务器在开始返回结果之前从集合或索引的开头开始走获取偏移量或跳过位置.随着偏移量(例如上面的 pageNumber)增加,cursor.skip() 将变得更慢并且 CPU 密集度更高.对于较大的集合,cursor.skip() 可能会成为 IO 绑定.

The cursor.skip() method is often expensive because it requires the server to walk from the beginning of the collection or index to get the offset or skip position before beginning to return result. As offset (e.g. pageNumber above) increases, cursor.skip() will become slower and more CPU intensive. With larger collections, cursor.skip() may become IO bound.

为了以可缩放的方式实现分页,结合 limit() 和至少一个过滤条件,createdOn 日期适合多种用途.

To achieve pagination in a scaleable way combine a limit( ) along with at least one filter criterion, a createdOn date suits many purposes.

MyModel.find( { createdOn: { $lte: request.createdOnBefore } } )
.limit( 10 )
.sort( '-createdOn' )

这篇关于如何在 Node.js 中使用 Mongoose 进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆