我正在用Node.js和mongoose写一个web应用程序。如何对我从.find()调用得到的结果进行分页?我想要一个功能可比的“限制50,100”在SQL。
当前回答
使用这个简单的插件。
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({}) //使用方法
其他回答
你可以使用一个叫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);
}
}
以上回答是正确的。
只是一个插件,任何人谁是异步等待而不是 承诺! !
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
});
}
};
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);
简单而强大的分页解决方案
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个文档。
这是一个你可以尝试的例子,
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
});
});
});
推荐文章
- Node.js -以平台不可知的方式查找主目录
- 为什么Node.js是单线程的?
- 比较mongoose _id和字符串
- .js和.mjs文件有什么区别?
- 如何修复npm UNMET PEER DEPENDENCY警告?
- 用ReactJS在localStorage中存储JWT安全吗?
- 用于XML解析的最佳节点模块
- Firebase Firestore“引用”数据类型的好处是什么?
- 如何让一个node.js应用程序永久运行?
- MongoDB:如何将多个集合中的数据合并为一个?
- 在npm install grunt——save-dev中-save-dev是什么意思
- 在Express.js中使用next()将变量传递给下一个中间件
- 如何Polyfill节点核心模块在webpack 5
- Router.use()需要中间件函数,但是得到了一个Object
- MongoDB - admin用户未授权