How to implement pagination for mongodb in node.js using official mongodb client?

前端 未结 4 1409
無奈伤痛
無奈伤痛 2021-01-16 02:34

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

4条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 03:11

    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);
        });
    });
    

    Here's a pagination function:

    function studentsPerPage (pageNumber, nPerPage) {
        return db.collection('students').find({}, 
            {
                limit: nPerPage, 
                skip: pageNumber > 0 ? ( ( pageNumber - 1 ) * nPerPage ) : 0
            });
    }
    

提交回复
热议问题