如何使用官方mongodb客户端在node.js中为mongodb实现分页? [英] How to implement pagination for mongodb in node.js using official mongodb client?
本文介绍了如何使用官方mongodb客户端在node.js中为mongodb实现分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为
I want to implement pagination for mongodb in node.js enviroment using offical mongodb package. I tried to find out on internet but all are mongoose based links. I dont want to use mongoose.
如何使用在
处提供的官方客户端api进行分页
http://mongodb.github.io/node-mongodb-native/3.1 /api/
How can I implement pagination using official client api given at
http://mongodb.github.io/node-mongodb-native/3.1/api/
推荐答案
Using the recommended pagination approach with limit() and skip() (see here):
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect('http:localhost:27017').then((client) => {
const db = client.db(mongo.db);
db.collection('my-collection').find({}, {limit:10, skip:0}).then((documents) => {
//First 10 documents
console.log(documents);
});
db.collection('my-collection').find({}, {limit:10, skip:10}).then((documents) => {
//Documents 11 to 20
console.log(documents);
});
});
这是一个分页功能:
function studentsPerPage (pageNumber, nPerPage) {
return db.collection('students').find({},
{
limit: nPerPage,
skip: pageNumber > 0 ? ( ( pageNumber - 1 ) * nPerPage ) : 0
});
}
这篇关于如何使用官方mongodb客户端在node.js中为mongodb实现分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文