Spearfisher Spearfisher - 3 months ago 18
Node.js Question

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?

Answer

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