Can Mongoose middleware populate then sort an array of references?

179 Views Asked by At

I'm trying to sort an internal array of document references in a document by the values in the referenced documents. I'd like to do this every time I run a query so if I can do this with a query sort() function or a post-find middleware that would be ideal (rather than having the code that calls the find needing to sort after the fact).

I have a schema for a ModSet that looks like this:

{
    // details excluded...

    categories:[{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Category"
    }]
}

The Category schema looks like this (irrelevant details excluded):

{
    // details excluded...

    name: {type:String, required:true},
    sortOrder: Number
}

I would like to make a find query for a ModSet and as part of the query, it should always sort the categories array by the sortOrder in the populated Category document.

As an example, today I run a find and populate query and get the following document back:

{
    categories: [
        {name: "categoryA", sortOrder: "5"},
        {name: "categoryB", sortOrder: "3"},
        {name: "categoryC", sortOrder: "1"},
        {name: "categoryD", sortOrder: "4"},
        {name: "categoryE", sortOrder: "2"}
    ]
}

What I want to get back is (sorted by categories.sortOrder):

{
    categories: [
        {name: "categoryC", sortOrder: "1"},
        {name: "categoryE", sortOrder: "2"},
        {name: "categoryB", sortOrder: "3"},
        {name: "categoryD", sortOrder: "4"},
        {name: "categoryA", sortOrder: "5"}
    ]
}
1

There are 1 best solutions below

0
Parth Tagadiya On

You can do it by following way.

User.find({})
  .populate('categories', 'name sortOrder', null, { sort: { 'sortOrder': -1 } })