How to sort in mongoose?

Philippe Rathé picture Philippe Rathé · Nov 29, 2010 · Viewed 292.2k times · Source

I find no doc for the sort modifier. The only insight is in the unit tests: spec.lib.query.js#L12

writer.limit(5).sort(['test', 1]).group('name')

But it doesn't work for me:

Post.find().sort(['updatedAt', 1]);

Answer

iwein picture iwein · Aug 5, 2015

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) { ... });