DS_COIMBRA
(Ds Coimbra)
February 24, 2021, 7:23pm
1
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!
aerabi
(Mohammad Ali A'râbi)
March 23, 2021, 12:35pm
2
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
Shahar_H
(Shahar H)
October 18, 2021, 8:15am
4
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.
You can write aggregator $sort for them. It worked for me.
Sample:
[
{ â$sortâ: {
âgroup.nameâ: 1
}
}
]