0

User Collection

[
  {
    username: 'user1'
  },
  {
    username: 'user2'
  },
  {
    username: 'user3'
  }
]

Sorting by sort method

const users = await User.find({}).sort({username: -1});
console.log(users[0].username);

Output

user3

Sorting by options of find method

const users = await User.find({}, null, {sort: {username: -1}});
console.log(users[0].username);

Output

user1

It's the same in mongodb console. I don't know why it doesn't work. I referenced from 'How to sort in mongoose?'

Partial the answer

...
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) { ... });
seongkuk han
  • 570
  • 6
  • 14

0 Answers0