Mongoose 分页和过滤器 [英] Mongoose Pagination and Filters
问题描述
我正在尝试使用 Mongoose 的可选过滤器选项进行分页.
I'm trying to trying to do pagination with an optional filter option with Mongoose.
我通过对数据库进行 2 次查询来处理分页,一次用于获取文档计数,另一次用于实际获取数据.没有分页,我的过滤器也能正常工作.我想知道有没有一种好方法可以从数据库中返回文档的计数以及数据的页面(将为当前页面显示的子集)?我如何设置查询来执行此操作?
I have it working with the pagination by making 2 queries to the database, one to get a count of the documents and one to actually get the data. Without pagination, my filters work properly as well. I was wondering is there a good way to return from the database both the count of the documents as well as a page (the subset that will be display for the current page) of the data? How could I setup the query to do this?
目前我正在拨打两个单独的电话:
Currently I'm making two separate calls:
Model.find(filter, selectPaths, {limit: limit, skip: skip}, callback);
Model.count(filter, another_callback);
我是否只需要两次调用即可获取我需要的所有数据?
Do I simply have to make two calls to get all the data I need?
推荐答案
我会冒昧地链接到我的其他答案:范围分页和使用mongodb和node.js进行分页.
I'll take the liberty and link to my other answers: ranged pagination and pagination with mongodb and node.js.
简短回答:不要使用跳过/限制,除非您的数据集很小(例如 <1000 个左右的文档).您获取的页面越大,它的性能就越差.使用范围查询(field: {$gt: value}
),它们效率更高(当然,如果有索引的话).
Short answer: don't use skip/limit, unless your datasets are small (like < 1000 documents or so). The greater page you fetch, the worse it will perform. Use range queries (field: {$gt: value}
), they are much more efficient (if indexed, of course).
不,您不能通过一次查询返回总数和部分数据.
And no, you can't return total count and part of the data with one query.
这篇关于Mongoose 分页和过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!