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.