Mehdi Faraji
Mehdi Faraji

Reputation: 3846

How to sort mongoose populated array by a value?

I get user schema ads by populating ads like this :

let user;
    try {
        user = await User.findOne({ _id: id }).populate('ads').sort([ [ 'date', -1 ] ]);
    } catch (e) {
        console.log('Could not post user : ' + e);
        return next(e);
    }

    res.json({
        ads: user.ads
    });

But the sort doesn't work .

How can I sort ads by their date value ?

Upvotes: 3

Views: 1662

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

Refer to the docs, you can do it with:

User.findOne({ _id: id }).populate({
  path: 'ads',
  options: { sort: { 'date': -1 } }
})

More infos about other options can be found here.

Upvotes: 5

Related Questions