Search code examples
javascriptnode.jsmongodbmongoosees6-promise

Mongoose: improve find() and count() query


Background

I have a query in Mongoose that finds a set of objects, and then returns these said objects together with the total number of them:

var itemsPerPage = 4, pageNum = 1;

Survey.find({})
    .limit(itemsPerPage)
    .skip(itemsPerPage * pageNum)
    .then(docs => {
        if (docs.length === 0)
            console.log("There are no results matching your query.");
        else
            DocModel.count({})
                .then(number => {
                    console.log(JSON.stringify({number, docs}));
                });
        })
        .catch(console.log);

To achieve this I do:

  1. find query with params
  2. use limit and skip to obtain results from correct page
  3. if docs is not empty, start a count query
  4. return information

Problem

The problem here, since I need pagination in the query, is that I have to make 2 separate requests to the DB (find and count) which can potential be very heavy.

To optimize this, I would like to avoid the count query, but I don't know how.

Another issue is the nested promises anti pattern, but that is not the issue I would like to focus on right now.

Question

I am open to any suggestions on improving this code you may have!


Solution

  • You can install mongoose paginate that makes it easier.

    npm install mongoose-paginate
    

    after that

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

    Hope this work for you. Thanks :-)