'Sort the data by the populated field by typegoose in mongodb

I have the three collections as following:

export class TopClass implements Base {
  @prop()
  name: string;

  @prop({ ref: () => SecondClass})
  second: SecondClass;
}
export class SecondClass implements Base {
  @prop()
  name: string;

  @prop({ ref: () => ThirdClass})
  third: ThirdClass;
}
export class ThirdClass implements Base {
  @prop()
  name: string;

  @prop()
  timestamp: number;
}

It is simple to retrieve the data in the "TopClass" by populate so that I can access the data by "topClass.second.third.timestamp" in the TypeScript. But I cannot sort the data for "TopClass" by the field "topClass.second.third.timestamp", how can I achieve it? For example, the result sort by "topClass.second.third.timestamp" should be:

// console.log(`${topClass.name} ${topClass.second.name} ${topClass.second.third.timestamp}`)
TopClassB, SecondClassB, 1648142800
TopClassA, SecondClassA, 1648142930
TopClassD, SecondClassD, 1648143055
TopClassC, SecondClassC, 1648143399

Not Working:

await this.topClassModel
  .find()
  .populate(...)
  .sort({ 'second.third.timestamp': 1 });

Requirement:

  1. sort the topClass by the populated field ('second.third.timestamp')
  2. TopClass should be populated so that I can access each field from the results (ex. topClass.second.third.timestamp)

I also try to use the aggregate but it seems to be difficult to achieve the requirement 2. Anyone can help me?



Solution 1:[1]

TL;DR: You cant use mongoose populate in a query, use aggregation instead.

This Question with plain mongoose, and the Answer still applies to this because typegoose only handles class to schema / model translation not actual operations.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hasezoey