How to sort in mongoose?
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 })
A sort can be done in any of the following ways in mongoose:
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 will be useful:
Post.find().sort([['updatedAt', 'descending']]).all(function (posts) { // do something with the array of posts });
// 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
})