I have a User model
var User = mongoose.model('Users',
mongoose.Schema({
username: 'string',
password: 'string',
rights: 'string'
})
);
I want to get all the users, sorted alphabetically by username. This is what I have tried
User.find({}, null, {sort: {username: 1}}, function (err, users) {
res.send(users);
});
However, this does not sort the users alphabetically. How can I sort alphabetically?
EDIT: I got confused because I was expecting a “purely alphabetically” sort from Mongoose, not one where Z > a. Basically, I wanted a sort based on username.toLowerCase().
EDIT: Per the comment the issue turns out to be sorting on
toLowerCase(username). MongoDB doesn’t have a built in method for complex sorting. So there are essentially two ways to go:usernameLowerCasefield to the Schema. This is the better option if you need to do this a lot.$toLoweroperator to dynamically generate ausernameLowerCasefield. This comes with performance and memory caveats, but it may be the more convenient choice.Original Answer: Here’s a complete example that sorts correctly using the specific code from the question. So there must be something else going on: