2

I'm creating a RESTful API that will return documents in a MongoDB collection. Being RESTful, I would like to limit the number of documents returned to 25, and then let the client ask for the next 25, and then the next, and so on until all documents have been read. Using find() I am able to get 'all' documents in a collection, and using find().limit() I can limit it to 25, but it will always get the first 25. Are there any good code examples out there showing how to remember where you left off in the find() so that the second call to find will return the next 25 documents in the collection? My code so far ...

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {        
    Transaction.find(function (err, transactions) {
        if (err) {
            mongoose.connection.close();                
            res.send('FAIL');
        } else {
            mongoose.connection.close();
            res.send(transactions);
        }            
    }).limit(25);
});

tx!

mscdex
  • 104,356
  • 15
  • 192
  • 153
lewiada
  • 1,397
  • 2
  • 10
  • 15

1 Answers1

6

Use skip:

var recordsPerPage = 25;

Transaction
    .find()
    .skip((currentPage - 1) * recordsPerPage)
    .limit(recordsPerPage)
    .exec(function (err, transactions) {
        res.send(transactions);
    });

skip will start returning results from the position parameter you pass in. So if you want, say, the results of page 3 (results 51 to 75), you just have to skip the 50 first results.

Komo
  • 2,043
  • 1
  • 22
  • 35