我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。
当前回答
你可以使用mongoose- pagate -v2。欲了解更多信息,请点击这里
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const mySchema = new mongoose.Schema({
// your schema code
});
mySchema.plugin(mongoosePaginate);
const myModel = mongoose.model('SampleModel', mySchema);
myModel.paginate().then({}) // Usage
其他回答
const ITEMS_PER_PAGE = 2;
exports.getProducts = (req, res, next) => {
// + will turn the string to a number
const page = +req.query.page || 1;
let totalItems;
//Product model
Product.find()
.countDocuments()
.then((numProducts) => {
totalItems = numProducts;
return Product.find()
//If query param is 3, since ITEMS_PER_PAGE = 2, we skip 2*2 items
// we show only 5th and 6th item
.skip((page - 1) * ITEMS_PER_PAGE)
.limit(ITEMS_PER_PAGE);
})
.then((products) => {
res.render("shop/products", {
// maybe sending the products object to templating engine
});
})
.catch((err) => {
const error = new Error(err);
error.httpStatusCode = 500;
// if you are set express error handler, use this
// when we call next() with an argument passed in, we let express know, we skip all other middlewares, we move to error handling middleware
return next(error);
});
};
使用猫鼬,快递和翡翠的分页-这里有一个链接到我的博客与更多的细节
var perPage = 10
, page = Math.max(0, req.params.page)
Event.find()
.select('name')
.limit(perPage)
.skip(perPage * page)
.sort({
name: 'asc'
})
.exec(function(err, events) {
Event.count().exec(function(err, count) {
res.render('events', {
events: events,
page: page,
pages: count / perPage
})
})
})
查询:
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);
});
});
你可以使用一个叫Mongoose Paginate的小包,让它更容易。
$ npm install mongoose-paginate
在你的路由或控制器后,只需添加:
/**
* querying for `all` {} items in `MyModel`
* paginating by second page, 10 items per page (10 results, page 2)
**/
MyModel.paginate({}, 2, 10, function(error, pageCount, paginatedResults) {
if (error) {
console.error(error);
} else {
console.log('Pages:', pageCount);
console.log(paginatedResults);
}
}
这是我在代码中做的
var paginate = 20;
var page = pageNumber;
MySchema.find({}).sort('mykey', 1).skip((pageNumber-1)*paginate).limit(paginate)
.exec(function(err, result) {
// Write some stuff here
});
我就是这么做的。
推荐文章
- 有没有办法修复包锁。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 ?