我是 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;
});
这是我的模型:
感谢您的帮助 !
Afaik 你不能按嵌套对象排序,但你可以unwind https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/ the notifications
数组,应用降序排序并重新组合结果。就像是:
.aggregate([
{ $match: { _id: new ObjectId(req.user._id) }},
{ $unwind: '$notifications' },
{ $sort: { 'notifications.date': -1 }},
{ $group: { _id: '$_id', notifications: { $push: '$notifications'}}}])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)