如何限制退回物品的数量? [英] How do I limit the number of returned items?

查看:62
本文介绍了如何限制退回物品的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

myModel.find({}, function(err, items) {
    console.log(items.length);    // Big number
});

如何将返回的项目限制为仅插入最近的10个项目?

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

推荐答案

在最新的猫鼬(撰写本文时为3.8.1)中,您做两件事的方式有所不同:(1)您必须将单个参数传递给sort( ),它必须是一组约束或仅一个约束,并且(2)execFind()消失了,取而代之的是exec().因此,对于猫鼬3.8.1,您可以执行以下操作:

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

这篇关于如何限制退回物品的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆