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:

Thank you for your help !
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'}}}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With