我正在使用Node.js和mongoose编写一个webapp。如何对从.find()
电话中获得的结果进行分页?我想在SQL中使用与"LIMIT 50,100"
相当的功能。
答案 0 :(得分:253)
我对这个问题中接受的答案感到非常失望。这不会扩展。如果您在cursor.skip()上阅读了精细打印:
cursor.skip()方法通常很昂贵,因为它要求服务器从集合或索引的开头走,以在开始返回结果之前获取偏移或跳过位置。随着偏移量(例如上面的pageNumber)的增加,cursor.skip()将变得更慢并且CPU密集度更高。对于较大的集合,cursor.skip()可能会成为IO绑定。
为了以可扩展的方式实现分页,将limit()与至少一个过滤条件结合起来,createdOn日期适用于多种用途。
MyModel.find( { createdOn: { $lte: request.createdOnBefore } } )
.limit( 10 )
.sort( '-createdOn' )
答案 1 :(得分:196)
通过Rodolphe提供的信息仔细研究了Mongoose API,我发现了这个解决方案:
MyModel.find(query, fields, { skip: 10, limit: 5 }, function(err, results) { ... });
答案 2 :(得分:77)
使用猫鼬,表达和玉的分页 - http://madhums.me/2012/08/20/pagination-using-mongoose-express-and-jade/
var perPage = 10
, page = Math.max(0, req.param('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
})
})
})
答案 3 :(得分:52)
你可以这样链:
var query = Model.find().sort('mykey', 1).skip(2).limit(5)
使用exec
query.exec(callback);
答案 4 :(得分:31)
您可以使用名为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);
}
}
答案 5 :(得分:28)
迟到总比没有好。
var pageOptions = {
page: req.query.page || 0,
limit: req.query.limit || 10
}
sexyModel.find()
.skip(pageOptions.page*pageOptions.limit)
.limit(pageOptions.limit)
.exec(function (err, doc) {
if(err) { res.status(500).json(err); return; };
res.status(200).json(doc);
})
在这种情况下,您可以将查询page
和/或limit
添加到您的http网址。样本?page=0&limit=25
<强>顺便说一句强>
分页以0
答案 6 :(得分:14)
查询;
搜索= productName,
Params;
页= 1
// Pagination
router.get("/search/:page", (req, res, next) => {
const resultsPerPage = 5;
const 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);
});
});
答案 7 :(得分:14)
这是您可以尝试此操作的示例,
var _pageNumber = 2,
_pageSize = 50;
Student.count({},function(err,count){
Student.find({}, null, {
sort: {
Name: 1
}
}).skip(_pageNumber > 0 ? ((_pageNumber - 1) * _pageSize) : 0).limit(_pageSize).exec(function(err, docs) {
if (err)
res.json(err);
else
res.json({
"TotalCount": count,
"_Array": docs
});
});
});
答案 8 :(得分:9)
尝试使用mongoose功能进行分页。限制是每页的记录数和页面数。
var limit = parseInt(body.limit);
var skip = (parseInt(body.page)-1) * parseInt(limit);
db.Rankings.find({})
.sort('-id')
.limit(limit)
.skip(skip)
.exec(function(err,wins){
});
答案 9 :(得分:8)
这就是我在代码
上所做的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
});
我就是这样做的。
答案 10 :(得分:5)
这是我附加到所有模型的版本。它取决于下划线以方便和异步性能。 opts允许使用mongoose语法进行字段选择和排序。
var _ = require('underscore');
var async = require('async');
function findPaginated(filter, opts, cb) {
var defaults = {skip : 0, limit : 10};
opts = _.extend({}, defaults, opts);
filter = _.extend({}, filter);
var cntQry = this.find(filter);
var qry = this.find(filter);
if (opts.sort) {
qry = qry.sort(opts.sort);
}
if (opts.fields) {
qry = qry.select(opts.fields);
}
qry = qry.limit(opts.limit).skip(opts.skip);
async.parallel(
[
function (cb) {
cntQry.count(cb);
},
function (cb) {
qry.exec(cb);
}
],
function (err, results) {
if (err) return cb(err);
var count = 0, ret = [];
_.each(results, function (r) {
if (typeof(r) == 'number') {
count = r;
} else if (typeof(r) != 'number') {
ret = r;
}
});
cb(null, {totalCount : count, results : ret});
}
);
return qry;
}
将其附加到您的模型架构。
MySchema.statics.findPaginated = findPaginated;
答案 11 :(得分:4)
一种可靠的实现方法是使用查询字符串从前端传递值。假设我们要获取 页面 #2 ,还要 limit 25个结果。
查询字符串如下所示:?page=2&limit=25 // this would be added onto your URL: http:localhost:5000?page=2&limit=25
让我们看看代码:
// We would receive the values with req.query.<<valueName>> => e.g. req.query.page
// Since it would be a String we need to convert it to a Number in order to do our
// necessary calculations. Let's do it using the parseInt() method and let's also provide some default values:
const page = parseInt(req.query.page, 10) || 1; // getting the 'page' value
const limit = parseInt(req.query.limit, 10) || 25; // getting the 'limit' value
const startIndex = (page - 1) * limit; // this is how we would calculate the start index aka the SKIP value
const endIndex = page * limit; // this is how we would calculate the end index
// We also need the 'total' and we can get it easily using the Mongoose built-in **countDocuments** method
const total = await <<modelName>>.countDocuments();
// skip() will return a certain number of results after a certain number of documents.
// limit() is used to specify the maximum number of results to be returned.
// Let's assume that both are set (if that's not the case, the default value will be used for)
query = query.skip(startIndex).limit(limit);
// Executing the query
const results = await query;
// Pagination result
// Let's now prepare an object for the frontend
const pagination = {};
// If the endIndex is smaller than the total number of documents, we have a next page
if (endIndex < total) {
pagination.next = {
page: page + 1,
limit
};
}
// If the startIndex is greater than 0, we have a previous page
if (startIndex > 0) {
pagination.prev = {
page: page - 1,
limit
};
}
// Implementing some final touches and making a successful response (Express.js)
const advancedResults = {
success: true,
count: results.length,
pagination,
data: results
}
// That's it. All we have to do now is send the `results` to the frontend.
res.status(200).json(advancedResults);
我建议将这种逻辑实现到中间件中,以便您可以将其用于各种路由/控制器。
答案 12 :(得分:2)
最简单快捷的方法是使用objectId进行分页 实施例;
初始加载条件
condition = {limit:12, type:""};
从响应数据中获取第一个和最后一个ObjectId
页面下一个条件
condition = {limit:12, type:"next", firstId:"57762a4c875adce3c38c662d", lastId:"57762a4c875adce3c38c6615"};
页面下一个条件
condition = {limit:12, type:"next", firstId:"57762a4c875adce3c38c6645", lastId:"57762a4c875adce3c38c6675"};
在猫鼬中
var condition = {};
var sort = { _id: 1 };
if (req.body.type == "next") {
condition._id = { $gt: req.body.lastId };
} else if (req.body.type == "prev") {
sort = { _id: -1 };
condition._id = { $lt: req.body.firstId };
}
var query = Model.find(condition, {}, { sort: sort }).limit(req.body.limit);
query.exec(function(err, properties) {
return res.json({ "result": result);
});
答案 13 :(得分:2)
有一些很好的答案可以给出使用skip()和limit()的解决方案,但是,在某些情况下,我们还需要文档计数才能生成分页。这是我们在项目中所做的:
all_countries = {
"Cambodia": "KH",
"Saint Kitts and Nevis": "KN",
"Comoros": "KM",
"Sao Tome and Principe": "ST",
"Slovakia": "SK",
"Korea, Republic of": "KR",
"Slovenia": "SI",
"Korea, Democratic People's Republic of": "KP",
"Kuwait": "KW",
"Senegal": "SN",
"Italy": "IT",
}
a = [["Pusan National University Hospital", "49241 Busan", "Korea", "Republic of"],
["Severance Hospital", "03722 Seoul", "Korea", "Republic of"],
["Ospedale degli Infermi", "47923 Rimini", "Italy"]]
def process_data(a):
ll = []
for row in a:
if len(row) == 3:
c = row[-1]
elif len(row) == 4:
c = row[-2]+', '+row[-1]
rr = row[0:2]+[all_countries[c]]
ll.append(rr)
return ll
process_data(a)
答案 14 :(得分:2)
最佳方法(IMO)是在有限的集合或文档中使用跳过和限制BUT。
要在有限的文档中进行查询,我们可以在DATE类型字段上使用特定的索引,如索引。见下文
let page = ctx.request.body.page || 1
let size = ctx.request.body.size || 10
let DATE_FROM = ctx.request.body.date_from
let DATE_TO = ctx.request.body.date_to
var start = (parseInt(page) - 1) * parseInt(size)
let result = await Model.find({ created_at: { $lte: DATE_FROM, $gte: DATE_TO } })
.sort({ _id: -1 })
.select('<fields>')
.skip( start )
.limit( size )
.exec(callback)
答案 15 :(得分:2)
最简单的分页插件。
https://www.npmjs.com/package/mongoose-paginate-v2
将插件添加到架构,然后使用模型分页方法:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate-v2');
var mySchema = new mongoose.Schema({
/* your schema definition */
});
mySchema.plugin(mongoosePaginate);
var myModel = mongoose.model('SampleModel', mySchema);
myModel.paginate().then({}) // Usage
答案 16 :(得分:2)
这是获取带有分页和限制选项的技能模型结果的示例函数
export function get_skills(req, res){
console.log('get_skills');
var page = req.body.page; // 1 or 2
var size = req.body.size; // 5 or 10 per page
var query = {};
if(page < 0 || page === 0)
{
result = {'status': 401,'message':'invalid page number,should start with 1'};
return res.json(result);
}
query.skip = size * (page - 1)
query.limit = size
Skills.count({},function(err1,tot_count){ //to get the total count of skills
if(err1)
{
res.json({
status: 401,
message:'something went wrong!',
err: err,
})
}
else
{
Skills.find({},{},query).sort({'name':1}).exec(function(err,skill_doc){
if(!err)
{
res.json({
status: 200,
message:'Skills list',
data: data,
tot_count: tot_count,
})
}
else
{
res.json({
status: 401,
message: 'something went wrong',
err: err
})
}
}) //Skills.find end
}
});//Skills.count end
}
答案 17 :(得分:2)
以上答案均成立。
对于那些进入异步等待而不是异步等待的人来说,只是一个附加组件 答应!
const findAllFoo = async (req, resp, next) => {
const pageSize = 10;
const currentPage = 1;
try {
const foos = await FooModel.find() // find all documents
.skip(pageSize * (currentPage - 1)) // we will not retrieve all records, but will skip first 'n' records
.limit(pageSize); // will limit/restrict the number of records to display
const numberOfFoos = await FooModel.countDocuments(); // count the number of records for that model
resp.setHeader('max-records', numberOfFoos);
resp.status(200).json(foos);
} catch (err) {
resp.status(500).json({
message: err
});
}
};
答案 18 :(得分:1)
简单而强大的分页解决方案
async getNextDocs(last_doc_id?: string) {
let docs
if (!last_doc_id) {
// get first 5 docs
docs = await MySchema.find().sort({ _id: -1 }).limit(5)
}
else {
// get next 5 docs according to that last document id
docs = await MySchema.find({ _id: { $lt: last_doc_id} }).sort({ _id: -1 }).limit(5)
}
return docs
}
答案 19 :(得分:1)
您也可以使用以下代码行
per_page = parseInt(req.query.per_page) || 10
page_no = parseInt(req.query.page_no) || 1
var pagination = {
limit: per_page ,
skip:per_page * (page_no - 1)
}
users = await User.find({<CONDITION>}).limit(pagination.limit).skip(pagination.skip).exec()
此代码将在最新版本的mongo中工作
答案 20 :(得分:0)
您可以使用mongoose-paginate-v2。有关更多信息,click here
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
答案 21 :(得分:0)
MongoDB 官方博客有一篇关于分页的条目,其中介绍了为什么“跳过”可能很慢并提供替代方案:How to draw a double empty ASCII rhombus?
答案 22 :(得分:0)
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.
答案 23 :(得分:0)
使用ts-猫鼬分页
const trainers = await Trainer.paginate(
{ user: req.userId },
{
perPage: 3,
page: 1,
select: '-password, -createdAt -updatedAt -__v',
sort: { createdAt: -1 },
}
)
return res.status(200).json(trainers)
答案 24 :(得分:0)
我找到了一个非常有效的方法并自己实现了,我认为这种方法是最好的,原因如下:
唯一需要注意的是,Mongoose 的一些方法,比如 .save()
不能很好地处理精益查询,这些方法列在这个 awesome blog post 中,我真的很推荐这个系列,因为它考虑了很多方面,例如类型安全(防止严重错误)和 PUT/PATCH。
我将提供一些上下文,这是一个 Pokémon 存储库,分页如下所示:API 从 Express 的 req.body
对象接收 unsafeId,我们需要将其转换为字符串以防止 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-One 错误,您可以按照以下方式进行操作,考虑到 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)的空数组,这太棒了!
答案 25 :(得分:0)
使用这个简单的插件。
https://github.com/WebGangster/mongoose-paginate-v2
安装
npm install mongoose-paginate-v2
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const mySchema = new mongoose.Schema({
/* your schema definition */
});
mySchema.plugin(mongoosePaginate);
const myModel = mongoose.model('SampleModel', mySchema);
myModel.paginate().then({}) // Usage
答案 26 :(得分:0)
也可以通过异步/等待来获得结果。
下面的代码示例使用带有hapi v17和mongoose v5的异步处理程序
{
method: 'GET',
path: '/api/v1/paintings',
config: {
description: 'Get all the paintings',
tags: ['api', 'v1', 'all paintings']
},
handler: async (request, reply) => {
/*
* Grab the querystring parameters
* page and limit to handle our pagination
*/
var pageOptions = {
page: parseInt(request.query.page) - 1 || 0,
limit: parseInt(request.query.limit) || 10
}
/*
* Apply our sort and limit
*/
try {
return await Painting.find()
.sort({dateCreated: 1, dateModified: -1})
.skip(pageOptions.page * pageOptions.limit)
.limit(pageOptions.limit)
.exec();
} catch(err) {
return err;
}
}
}
答案 27 :(得分:0)
**//localhost:3000/asanas/?pageNo=1&size=3**
//requiring asanas model
const asanas = require("../models/asanas");
const fetchAllAsanasDao = () => {
return new Promise((resolve, reject) => {
var pageNo = parseInt(req.query.pageNo);
var size = parseInt(req.query.size);
var query = {};
if (pageNo < 0 || pageNo === 0) {
response = {
"error": true,
"message": "invalid page number, should start with 1"
};
return res.json(response);
}
query.skip = size * (pageNo - 1);
query.limit = size;
asanas
.find(pageNo , size , query)
.then((asanasResult) => {
resolve(asanasResult);
})
.catch((error) => {
reject(error);
});
});
}
答案 28 :(得分:0)
app.get("/:page",(req,res)=>{
post.find({}).then((data)=>{
let per_page = 5;
let num_page = Number(req.params.page);
let max_pages = Math.ceil(data.length/per_page);
if(num_page == 0 || num_page > max_pages){
res.render('404');
}else{
let starting = per_page*(num_page-1)
let ending = per_page+starting
res.render('posts', {posts:data.slice(starting,ending), pages: max_pages, current_page: num_page});
}
});
});
答案 29 :(得分:0)
如果您使用猫鼬作为休息api的来源,请查看 'restify-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
所以基本上你会得到一个通用服务器,它具有相对线性的加载时间来查询集合。如果您想进入自己的实现,那就太棒了。
答案 30 :(得分:0)
您可以使用skip()和limit(),但效率非常低。更好的解决方案是对索引字段加上limit()进行排序。 我们Wunderflats在这里发布了一个小型库:https://github.com/wunderflats/goosepage 它使用第一种方式。
答案 31 :(得分:0)
您可以像这样编写查询。
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);
}
});
页面:来自客户端的页码作为请求参数 per_page:每页显示的结果没有
如果你正在使用MEAN堆栈,那么博客帖子提供了很多信息,可以使用angular-UI bootstrap在前端创建分页,并在后端使用mongoose skip和limit方法。
请参阅:https://techpituwa.wordpress.com/2015/06/06/mean-js-pagination-with-angular-ui-bootstrap/