Mongoose - How to sort a query based on a populated field

I have the following User:

{
    username: String,
    password: String,
    group: {
      type: Schema.Types.ObjectId,
      ref: "Group"
    }
}

Then i have the following Group:

{    
    nome: String,
    code: String,
}

I want to sort a collection of Users by the name of their Group, alphabetically.

I am currently doing this:

UserModel.find({key, skip, limit}).populate({ path: "group", select: "nome" }).sort({"group.nome": "asc"})

But it is not sorting at all.

Thank you for your help!

I guess it’s too late, but have you tried this?:

const options = { sort: [['group.name', 'asc' ]] };

UserModel.find({})
  .populate({ path: 'group', select: 'nome', options })
  ...

I get Invalid sort() argument, must be array of arrays

2 Likes

This worked for me:
options:{ sort: [{‘name’, ‘asc’ }] }

2 Likes

How about this

const UserSchema = new Schema(
{
email: {
type: String,
required: true,
lowercase: true,
trim: true,
minlength: 6,
maxlength: 40,
},
password: { type: String, required: true },
});

UserSchema.virtual(“followers”, {
ref: “Follow”,
localField: “_id”,
foreignField: “following”,
count: true, // Only get the number of docs !!important
});

UserSchema.virtual(“history”, {
ref: “History”,
localField: “_id”,
foreignField: “user”,
count: true, // Only get the number of docs !!important
});

leaderboard({ offset, limit }) {
return this.model
.find()
.populate({ path: “followers” })
.populate({ path: “history” })
.sort({ followers: “asc”, history: “desc” })
.skip(offset)
.limit(limit)
.exec();
}

not working as expected.