1

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)
Ajith
  • 2,476
  • 2
  • 17
  • 38

0 Answers0