我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。
当前回答
const page = req.query.page * 1 || 1;
const limit = req.query.limit * 1 || 1000;
const skip = (page - 1) * limit;
query = query.skip(skip).limit(limit);
其他回答
let page,limit,skip,lastPage, query;
page = req.params.page *1 || 1; //This is the page,fetch from the server
limit = req.params.limit * 1 || 1; // This is the limit ,it also fetch from the server
skip = (page - 1) * limit; // Number of skip document
lastPage = page * limit; //last index
counts = await userModel.countDocuments() //Number of document in the collection
query = query.skip(skip).limit(limit) //current page
const paginate = {}
//For previous page
if(skip > 0) {
paginate.prev = {
page: page - 1,
limit: limit
}
//For next page
if(lastPage < counts) {
paginate.next = {
page: page + 1,
limit: limit
}
results = await query //Here is the final results of the query.
MongoDB官方博客有一个关于分页的条目,在那里他们解释了为什么“跳过”可能会很慢,并提供了替代方案:https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-1
你可以像这样串起来:
var query = Model.find().sort('mykey', 1).skip(2).limit(5)
使用exec执行查询
query.exec(callback);
我对这个问题的公认答案感到非常失望。这是无法缩放的。如果你读了游标上的小字。跳过():
cursor.skip()方法通常开销很大,因为它需要服务器从集合或索引的开始处遍历以获得偏移或跳过位置,然后才开始返回结果。随着偏移量(例如上面的pageNumber)的增加,cursor.skip()将变得更慢,更消耗CPU。对于较大的集合,cursor.skip()可能成为IO绑定。
要以可伸缩的方式将limit()与至少一个筛选条件结合起来实现分页,createdOn日期适合多种用途。
MyModel.find( { createdOn: { $lte: request.createdOnBefore } } )
.limit( 10 )
.sort( '-createdOn' )
我发现了一种非常有效的方法并亲自实施,我认为这种方法是最好的,原因如下:
它不使用跳过,这使得时间复杂度不能很好地扩展; 它使用id来查询文档。在MongoDB中,id默认情况下是索引的,这使得查询它们非常快; 它使用精益查询,这些被认为是非常具有执行力的,因为他们从Mongoose中删除了很多“魔法”,并返回一个来自MongoDB的“原始”文档; 它不依赖于任何可能包含漏洞或具有易受攻击依赖项的第三方包。
唯一需要注意的是,Mongoose的一些方法,比如.save()在精益查询中不能很好地工作,这些方法在这篇很棒的博客文章中列出了,我真的推荐这个系列,因为它考虑了很多方面,比如类型安全(防止严重错误)和PUT/ PATCH。
我将提供一些上下文,这是一个Pokémon存储库,分页工作如下:API从req接收unsafeId。Express的body对象,我们需要将其转换为字符串以防止NoSQL注入(它可以是一个带有邪恶过滤器的对象),这个unsafeId可以是一个空字符串或上一页最后一项的ID,它是这样的:
/**
* @description GET All with pagination, will return 200 in success
* and receives the last ID of the previous page or undefined for the first page
* Note: You should take care, read and consider about Off-By-One error
* @param {string|undefined|unknown} unsafeId - An entire page that comes after this ID will be returned
*/
async readPages(unsafeId) {
try {
const id = String(unsafeId || '');
let criteria;
if (id) {
criteria = {_id: {$gt: id}};
} // else criteria is undefined
// This query looks a bit redundant on `lean`, I just really wanted to make sure it is lean
const pokemon = await PokemonSchema.find(
criteria || {},
).setOptions({lean: true}).limit(15).lean();
// This would throw on an empty page
// if (pokemon.length < 1) {
// throw new PokemonNotFound();
// }
return pokemon;
} catch (error) {
// In this implementation, any error that is not defined by us
// will not return on the API to prevent information disclosure.
// our errors have this property, that indicate
// that no sensitive information is contained within this object
if (error.returnErrorResponse) {
throw error;
} // else
console.error(error.message);
throw new InternalServerError();
}
}
现在,为了消费它并避免前端的off - by - 1错误,你可以像下面这样做,考虑到pokemons是从API返回的Pokémons文档的数组:
// Page zero
const pokemons = await fetchWithPagination({'page': undefined});
// Page one
// You can also use a fixed number of pages instead of `pokemons.length`
// But `pokemon.length` is more reliable (and a bit slower)
// You will have trouble with the last page if you use it with a constant
// predefined number
const id = pokemons[pokemons.length - 1]._id;
if (!id) {
throw new Error('Last element from page zero has no ID');
} // else
const page2 = await fetchWithPagination({'page': id});
这里需要注意的是,Mongoose ID总是连续的,这意味着任何新的ID总是比旧的ID大,这是这个答案的基础。
这种方法已经针对Off-By-One错误进行了测试,例如,页面的最后一个元素可能会作为下一个页面的第一个元素返回(重复),或者位于上一页最后一个元素和当前页面第一个元素之间的元素可能会消失。
当您处理完所有页面并在最后一个元素(一个不存在的元素)之后请求一个页面时,响应将是一个200 (OK)的空数组,这太棒了!
推荐文章
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- 无法连接到服务器127.0.0.1:27017
- 如何使用npm全局安装一个模块?
- 实时http流到HTML5视频客户端的最佳方法
- 使用node.js下载图像
- Node.js Express中的HTTP GET请求
- Node.js:将文本文件读入数组。(每一行都是数组中的一项。)
- npm犯错!错误:EPERM:操作不允许,重命名
- Node Sass还不支持当前环境:Linux 64位,带false
- 我如何添加环境变量启动。VSCode中的json
- 如何创建数据库的MongoDB转储?
- 如何将MongoDB作为Windows服务运行?
- 解析错误:无法读取文件“…/tsconfig.json”.eslint
- 在Node.js中'use strict'语句是如何解释的?
- 当WebSockets可用时,为什么要使用AJAX ?