How to sort in mongoose?
In Mongoose, a sort can be done in any of the following ways:
Post.find({}).sort('test').exec(function(err, docs) { ... });
Post.find({}).sort([['date', -1]]).exec(function(err, docs) { ... });
Post.find({}).sort({test: 1}).exec(function(err, docs) { ... });
Post.find({}, null, {sort: {date: 1}}, function(err, docs) { ... });
This is how I got sort to work in mongoose 2.3.0 :)
// Find First 10 News Items
News.find({
deal_id:deal._id // Search Filters
},
['type','date_added'], // Columns to Return
{
skip:0, // Starting Row
limit:10, // Ending Row
sort:{
date_added: -1 //Sort by Date Added DESC
}
},
function(err,allNews){
socket.emit('news-load', allNews); // Do something with the array of 10 objects
})
As of Mongoose 3.8.x:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
Where:
criteria
can be asc
, desc
, ascending
, descending
, 1
, or -1
Note: Use quotation marks or double quote
use "asc"
, "desc"
, "ascending"
, "descending"
, 1
, or -1