Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose sort nested array of object not working

I'm new with NodeJS and MongoDB and I encounter an issue when I want to execute a Find() query with a Sort() using Mongoose.

I would like to sort my results by notifications date and it doesn't work

Here's my Query:

UsersNotifications
            .find({user_id: new ObjectId(req.user._id)})
            .sort({'notifications.date': -1})
            .select('notifications').exec().then(usersNotifications => {
                res.locals.usersNotifications = usersNotifications;
            });

Here's my models:

enter image description here

Thank you for your help !

like image 998
Stefano Martines Avatar asked Oct 22 '25 19:10

Stefano Martines


1 Answers

Afaik you cannot sort by nested objects, but you could unwind the notifications array, apply your descending sort and regroup the result. Something like:

.aggregate([
    { $match: { _id: new ObjectId(req.user._id) }},
    { $unwind: '$notifications' },
    { $sort: { 'notifications.date': -1 }},
    { $group: { _id: '$_id', notifications: { $push: '$notifications'}}}])
like image 194
eol Avatar answered Oct 25 '25 08:10

eol