猫鼬排序嵌套对象数组不起作用

时间:2020-06-12 13:44:35

标签: node.js mongodb mongoose

我是NodeJS和MongoDB的新手,当我想使用Mongoose使用Sort()执行Find()查询时遇到一个问题。

我想按通知日期对搜索结果进行排序,但它不起作用

这是我的查询

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

这是我的模特:

enter image description here

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

Afaik您无法按嵌套对象排序,但是可以unwind notifications数组,应用降序排序并重新组合结果。像这样:

.aggregate([
    { $match: { _id: new ObjectId(req.user._id) }},
    { $unwind: '$notifications' },
    { $sort: { 'notifications.date': -1 }},
    { $group: { _id: '$_id', notifications: { $push: '$notifications'}}}])