Mongoose - Cannot populate with sort on path notifications.from because it is a subproperty of a document array Mongoose - Cannot populate with sort on path notifications.from because it is a subproperty of a document array mongoose mongoose

Mongoose - Cannot populate with sort on path notifications.from because it is a subproperty of a document array


From Mongoose V5.0.12 FAQ : http://mongoosejs.com/docs/faq.html#populate_sort_order

Q. I'm populating a nested property under an array like the below code:

new Schema({ arr: [{ child: { ref: 'OtherModel', type: Schema.Types.ObjectId } }] });

.populate({ path: 'arr.child', options: { sort: 'name' } }) won't sort by arr.child.name?

A. See this GitHub issue. It's a known issue but one that's exceptionally difficult to fix.

So unfortunately, for now, it's not possible,

One way to achieve this is to simply use javascript's native sort to sort the notifications after fetching.

.exec(function(err, user) {    if (err) console.log(err)    user.notifications.sort(function(a, b){         return new Date(b.date) - new Date(a.date);    });})


It can be achievable using nesting populate like this - eg - schema - {donationHistory: {campaignRequestId: [ref ids]}}await user.populate({        path: 'donationHistory.campaignRequestId',        populate: [{            path: 'campaignRequestId',            model: 'CampaignRequest',            options: { sort: { 'createdAt': -1 } },        }],        ...deepUserPopulation,    }).execPopulate();