简体   繁体   中英

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 ?

Refer to thedocs , 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM