0

I am writing a Node.JS app with MongoDB. One of the things I need to implement is the listing of the objects. I've already implemented the pagination using the skip() and limit() functions, thanks to this answer:

myModel.find()
  .skip(offset)
  .limit(limit)
  .exec(function (err, doc) {
     // do something with objects
  })

The thing is, I want my endpoint to return metadata, and one of the fields I need is a boolean representing if there are more objects that can be loaded.

The most simple way to implement this is just loading one more object (to determine if there are more objects to display) and not showing it to the user, something like that:

 myModel.find()
  .skip(offset)
  .limit(limit + 1)
  .exec(function (err, doc) {
    var moreAvailable; // are there more documents? 
    if (doc.length > limit) {
      moreAvailable = true;
      doc.length = limit; // don't show the last object to the user
    } else {
      moreAvailable = false;
    }


  })

But I'm pretty sure that there should be more clever way to do this. Is it?

Community
  • 1
  • 1
serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76
  • 3
    Asking for one extra object is IMO the most efficient way of handling pagination in MongoDB. I had a lot of issues (performance wise) when trying to use count for this purpose (which is pretty much standard in SQL databases), whilst a skip + limit for the same query was super fast. Unless you need to know exactly how many pages you have, this would be a sufficient solution. – jishi Mar 10 '17 at 08:18
  • Hi. I'm having some issues replication your solution – Mhd Apr 04 '22 at 13:20

1 Answers1

-2

Use db.collection.find(<query>).count() https://docs.mongodb.com/manual/reference/method/cursor.count/

var total = db.collection.find(<query>).count();
var is_more = total > skip + limit;
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
  • 1
    Try to avoid count! Count is super inefficient as soon as you are using a query, and behaves erratically even when matching an index. – jishi Mar 10 '17 at 08:16