node.js - Mongoose 排序嵌套的对象数组不起作用

标签 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

感谢您的帮助!

最佳答案

Afaik 你不能按嵌套对象排序,但你可以 unwind notifications 数组,应用降序排序并重新组合结果。像这样的东西:

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

关于node.js - Mongoose 排序嵌套的对象数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62345528/

相关文章:

python - 如何使用 pymongo 编写连接到 mongodb 的函数

javascript - 从 mongodb Node js 搜索记录时出现问题?

node.js - 错误: Cannot read property '_id' of undefined

javascript - 测试 Mongoose 模型是否有意义?

node.js - Mongoose 嵌套模式验证不起作用

arrays - 如何在js中从数组中删除元素[元素来自mongodb]

debugging - 如何以编程方式检测nodejs中的 Debug模式?

node.js - 根据列表中的值查询模型

javascript - 您如何使用 NVM 处理多个 Node 版本和多个项目?

javascript - 声明可在 Nodejs、浏览器、commonJS 和 AMD 中工作的 javascript 独立库的正确方法是什么?