我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。
当前回答
实现这一点的可靠方法是使用查询字符串从前端传递值。假设我们想要获得第2页,并将输出限制为25个结果。 page=2&limit=25 //这将被添加到您的URL: http:localhost:5000?= 2限制= 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);
我建议将这个逻辑实现到中间件中,这样你就可以将它用于各种路由/控制器。
其他回答
最好的方法(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)
你可以像这样串起来:
var query = Model.find().sort('mykey', 1).skip(2).limit(5)
使用exec执行查询
query.exec(callback);
你可以使用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
简单而强大的分页解决方案
async getNextDocs(no_of_docs_required: number = 5, last_doc_id?: string) {
let docs
if (!last_doc_id) {
// get first 5 docs
docs = await MySchema.find().sort({ _id: -1 }).limit(no_of_docs_required)
}
else {
// get next 5 docs according to that last document id
docs = await MySchema.find({_id: {$lt: last_doc_id}})
.sort({ _id: -1 }).limit(no_of_docs_required)
}
return docs
}
Last_doc_id:您获得的最后一个文档id
No_of_docs_required:你想要获取的文档数量,例如5、10、50等。
如果你不提供last_doc_id给方法,你会得到5个最新的文档 如果你提供了last_doc_id,那么你会得到下一个,即5个文档。
也可以用async/await实现结果。
下面的代码示例使用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;
}
}
}
推荐文章
- npm犯错!代码UNABLE_TO_GET_ISSUER_CERT_LOCALLY
- Access-Control-Allow-Origin不允许Origin < Origin >
- 如何获得所有已注册的快捷路线?
- 你可以为你的组织托管一个私有的存储库来使用npm吗?
- 如何定位父文件夹?
- Gulp命令未找到-安装Gulp后错误
- 在Node.js中写入文件时创建目录
- MongoDB在v4之前不兼容ACID意味着什么?
- 如何将自定义脚本添加到包中。Json文件,运行javascript文件?
- 使用child_process。execSync但保持输出在控制台
- 显示所有集合中的所有内容
- SyntaxError:在严格模式下使用const
- 在Node.js中递归复制文件夹
- 如何在node.js中设置默认时区?
- “react-scripts”不被视为内部或外部命令