提问者:小点点

对象的猫鼬排序嵌套数组不工作


我是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;
            });

这是我的模型:

谢谢你的帮助!


共1个答案

匿名用户

虽然不能按嵌套对象进行排序,但可以展开通知数组,应用降序排序并重新组合结果。 类似于:

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