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); }); } );
mjhm
source share