如何使用官方mongodb客户端在node.js中为mongodb实现分页? [英] How to implement pagination for mongodb in node.js using official mongodb client?

查看:211
本文介绍了如何使用官方mongodb客户端在node.js中为mongodb实现分页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 mongodb 实现分页en.wikipedia.org/wiki/Node.js"rel =" nofollow noreferrer> node.js 环境,使用 mongoose 的链接.我不想用猫鼬.

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/

推荐答案

将建议的分页方法与limit()和skip()(

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆