4

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 !

1 Answer 1

6

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'}}}])
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! It work as expected :) Thank you very much
Great, happy to help! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.