我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。
当前回答
查询:
search = productName
参数:
page = 1
// Pagination
router.get("/search/:page", (req, res, next) => {
const resultsPerPage = 5;
let page = req.params.page >= 1 ? req.params.page : 1;
const query = req.query.search;
page = page - 1
Product.find({ name: query })
.select("name")
.sort({ name: "asc" })
.limit(resultsPerPage)
.skip(resultsPerPage * page)
.then((results) => {
return res.status(200).send(results);
})
.catch((err) => {
return res.status(500).send(err);
});
});
其他回答
MongoDB官方博客有一个关于分页的条目,在那里他们解释了为什么“跳过”可能会很慢,并提供了替代方案:https://www.mongodb.com/blog/post/paging-with-the-bucket-pattern--part-1
您可以像这样编写查询。
mySchema.find().skip((page-1)*per_page).limit(per_page).exec(function(err, articles) {
if (err) {
return res.status(400).send({
message: err
});
} else {
res.json(articles);
}
});
Page:来自客户端作为请求参数的页码。 Per_page:每页显示的结果数目
如果你正在使用MEAN堆栈,下面的博客文章提供了很多信息,在前端使用angular-UI引导和在后端使用猫鼬跳过和限制方法创建分页。
参见:https://techpituwa.wordpress.com/2015/06/06/mean-js-pagination-with-angular-ui-bootstrap/
你可以像这样串起来:
var query = Model.find().sort('mykey', 1).skip(2).limit(5)
使用exec执行查询
query.exec(callback);
如果你正在使用mongoose作为一个restful api的源,请看看 ' retify -mongoose'和它的查询。它内置了这个功能。
集合上的任何查询都提供了在这里有用的标头
test-01:~$ curl -s -D - localhost:3330/data?sort=-created -o /dev/null
HTTP/1.1 200 OK
link: </data?sort=-created&p=0>; rel="first", </data?sort=-created&p=1>; rel="next", </data?sort=-created&p=134715>; rel="last"
.....
Response-Time: 37
所以基本上你得到了一个通用服务器,它对集合的查询具有相对线性的加载时间。这是非常棒的,如果你想要进行自己的实现,可以参考一下。
使用这个简单的插件。
https://github.com/WebGangster/mongoose-paginate-v2
安装
NPM安装mongoose- pagate -v2 使用 添加插件到一个模式,然后使用模型paginate方法:
Const mongoose = require('mongoose'); const mongoosePaginate = require(' mongoosePaginate -v2'); const mySchema =新的猫鼬。模式({ /*你的模式定义*/ }); mySchema.plugin (mongoosePaginate); const myModel =猫鼬。模型(SampleModel, mySchema); myModel.paginate().then({}) //使用方法
推荐文章
- 在MongoDB中查找重复的记录
- 禁用包的postinstall脚本
- 为什么MongoDB Java驱动在条件中使用随机数生成器?
- Node.js上的html解析器
- 错误:无法找到模块“webpack”
- 在node.js中使用async / await文件系统
- NodeJS -用NPM安装错误
- 如何为本地安装npm包设置自定义位置?
- 回调函数来处理管道的完成
- Express函数中的“res”和“req”参数是什么?
- node.js TypeError:路径必须是绝对路径或指定根路径到res.sendFile[解析JSON失败]
- Passport.js -错误:序列化用户到会话失败
- Node.js vs .Net性能
- 从电子应用程序中删除菜单栏
- 如何用node.js实现一个安全的REST API