Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order and limit results in a query with a callback

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?

like image 786
Spearfisher Avatar asked Mar 16 '14 19:03

Spearfisher


1 Answers

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){

});

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
});
like image 185
Will Shaver Avatar answered Sep 28 '22 23:09

Will Shaver