排序和限制结果在带有回调的查询中 [英] Order and limit results in a query with a callback

查看:54
本文介绍了排序和限制结果在带有回调的查询中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Mongoose,我想对MongoDB进行查询并排序和限制得到的结果.我正在使用Node.js进行此操作,因此我正在使用回调.

Using Mongoose, I'd like to make a query with MongoDB and order and limit the results I get. I am doing this with Node.js so I am using callbacks.

到目前为止,我已经设法将结果排序如下:

So far, I have managed to order my results like this:

  myModel.find({ $query: {}, $orderby: { created_at : -1 }}, function (err, items) {
    callback( null, items )
  });  

如何限制选择的结果和索引以及要获取的项目数?

How can I limit the results I get selecting and index and the number of items I want to get?

推荐答案

使用mongodb native: http://mongodb.github.io/node-mongodb -native/api-generation/collection.html#find

Using mongodb native: http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#find

myModel.find(filter)
            .limit(pageSize)
            .skip(skip)
            .sort(sort)
            .toArray(callback);

您还可以在查询中指定项目:

You can also specify the items in your query:

myModel.find(filter, {sort: {created_at: -1}, limit: 10}, function(err, items){

});

在mongodb本机节点中没有$ orderby,因此我不确定您使用的是哪个库或其他工具.

There is no $orderby in node mongodb native, so I'm not sure what library or other tool you're using.

...

现在您已经弄清了猫鼬(通常我建议反对):

Now that you've clarified Mongoose (which in general I recommend against):

myModel.find(filter).limit(10).exec(function(err, items){
//process
});

这篇关于排序和限制结果在带有回调的查询中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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