How do I limit the number of returned items?

前端 未结 7 2014
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 15:32
myModel.find({}, function(err, items) {
    console.log(items.length);    // Big number
});

How can I limit the returned items to only the latest

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 16:07

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

提交回复
热议问题