How do I limit the number of returned items?

Running Turtle picture Running Turtle · Apr 29, 2011 · Viewed 116.2k times · Source
myModel.find({}, function(err, items) {
    console.log(items.length);    // Big number
});

How can I limit the returned items to only the latest 10 items that were inserted?

Answer

marni picture marni · Dec 15, 2013

In the latest mongoose (3.8.1 at the time of writing), you do two things differently: (1) you have to pass single argument to sort(), which must be an array of constraints or just one constraint, and (2) execFind() is gone, and replaced with exec() instead. Therefore, with the mongoose 3.8.1 you'd do this:

var q = models.Post.find({published: true}).sort({'date': -1}).limit(20);
q.exec(function(err, posts) {
     // `posts` will be of length 20
});

or you can chain it together simply like that:

models.Post
  .find({published: true})
  .sort({'date': -1})
  .limit(20)
  .exec(function(err, posts) {
       // `posts` will be of length 20
  });