I am trying to sort a populated document by the populated fields, similar to the example in the mongoose docs:
http://mongoosejs.com/docs/api.html#query_Query-populate
Where Kitten references owner by objectId and a query on Kitten is able to be sorted by the owner name. I've tried numerous variations of the syntax, such as from the answers given in
How to sort a populated document in find request?
While all of them populate and do not throw any errors, the sort option is not working for me. The one solution I have not tried yet is given here:
Mongoose, sort based on foreign/populated key
But does not use the available functionality of populate from mongoose and feels like a work around. Maybe a pair of fresh eyes could point out my problem.
My models (Semester and SemesterReference):
var semesterSchema = mongoose.Schema({
year: Number,
season: {
type: String,
enum: ["FALL", "SPRING", "SUMMER"]
}
});
var semesterReferenceSchema = mongoose.Schema({
name: String,
semester: {type: mongoose.Schema.Types.ObjectId, ref:"Semester"}
});
Result when I query with this code
schema.SemesterReference.find().populate({path: "semester", options: {sort: {"year": 1}}}).exec().then(function(result){
console.log(result);
})
[ { _id: 5b2bb2312731613ba06b0e8f,
name: 'ZZZ',
semester:
{ _id: 5b23bd1e0ffe9a29d02ee02c,
year: 2019,
season: 'SPRING',
__v: 0 },
__v: 0 },
{ _id: 5b2bb24b3c19bd1f3c1b0d66,
name: 'AAA',
semester:
{ _id: 5b23bd1e0ffe9a29d02ee011,
year: 2010,
season: 'SPRING',
__v: 0 },
__v: 0 } ]
The query returns the same result as if I had not specified sorting by year in options at all. I have tried the same query without quotes around semester or year, which does not work either. Worryingly, changing "year" in the query above to a string that does not match a property of semester (such as asdf) does not throw any errors and the query returns as normal, which seems to indicate that the sort option is being ignored.
I am on version 5.1.6 of mongoose and 3.6.0 of mongodb.