Mongoose: sort alphabetically

I have a User model

 var User = mongoose.model('Users', mongoose.Schema({ username: 'string', password: 'string', rights: 'string' }) ); 

I want to get all users sorted alphabetically by username . This is what I tried

 User.find({}, null, {sort: {username: 1}}, function (err, users) { res.send(users); }); 

However, this does not sort users alphabetically. How can I sort alphabetically?

EDIT . I got confused because I was expecting a "purely alphabetical" look from Mongoose, and not from where Z > a . Basically, I need a type based on username.toLowerCase() .

+7
source share
2 answers

EDIT: by comment, the problem turns out to be sorting by toLowerCase(username) . MongoDB does not have a built-in method for complex sorting. So there are two ways:

  • Add the usernameLowerCase field to the schema. This is the best option if you need to do this a lot.
  • Aggregate using the $toLower operator to dynamically create the usernameLowerCase field. This is due to performance and memory characteristics, but it may be a more convenient choice.

Original answer: Here is a complete example that sorts correctly using the specific code from the question. So there must be something else:

 #! /usr/bin/node var mongoose = require('mongoose'); mongoose.connect('localhost', 'test'); var async = require('async'); var User = mongoose.model('Users', mongoose.Schema({ username: 'string', password: 'string', rights: 'string' }) ); var userList = [ new User({username: 'groucho', password: 'havacigar', rights: 'left'}), new User({username: 'harpo', password: 'beepbeep', rights: 'silent'}), new User({username: 'chico', password: 'aintnosanityclause', rights: 'all'}) ]; async.forEach(userList, function (user, SaveUserDone) { user.save(SaveUserDone); }, function (saveErr) { if (saveErr) { console.log(saveErr); process.exit(1); } User.find({}, null, {sort: {username: 1}}, function (err, users) { if (err) { console.log(err); process.exit(1); } console.log(users); process.exit(0); }); } ); 
+10
source

This question and answer is several years old, and from what I can say, now there is the right way to do this. Providing this for future search engines:

 User.find().collation({locale:'en',strength: 2}).sort({username:1}) .then( (users) =>{ //do your stuff }); 

You can also index username without case sensitivity:

 UserSchema.index({username:1}, {collation: { locale: 'en', strength: 2}}); 

strength:1 - another option - it’s best to consult the documentation to decide which one is best for you.

Read more about this here.

+5
source

All Articles