'How to sort data based on entry of parent collection in mongodb using mongooose package

How to sort data based on entry of parent collection in mongodb using mongoose package.

My schema is organised as given below

Profile Schema

const mongoose      = require('mongoose');
const profileSchema = new mongoose.Schema(
    {
        fullName: {
            type: String,
            default:"",
            trim: true
        },
        school: {
            type: mongoose.Schema.Types.ObjectId,
            ref:'School',
            default:null
        },
    },
    { timestamps: true }
);

module.exports          = mongoose.model("Profile",profileSchema);

School Schema

const mongoose     = require('mongoose');
const schoolSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            default:"",
            trim: true
        }
    },
    { timestamps: true }
);

module.exports          = mongoose.model("School",schoolSchema);

My sort based on profile name works correctly from the below mongoose query

profiles = await Profile.find({})
                              .populate('school','_id name') 
                              .sort({fullName:-1})
                              .skip(skip).limit(per_page);

When I tried to sort based on school name it did'nt works , i have tried the code below, please help me to fix this issue

profiles = await Profile.find({})
                              .populate('school','_id name') 
                              .sort("-school.name") // Also tried "school.name"
                              .skip(skip).limit(per_page)


Sources

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

Source: Stack Overflow

Solution Source