Node.js Mongoose排序对象的嵌套数组不工作
我不熟悉NodeJS和MongoDB,当我想使用Mongoose执行带有Sort()的Find()查询时,遇到了一个问题 我想按通知日期对结果排序,但它不起作用 我的问题是:Node.js Mongoose排序对象的嵌套数组不工作,node.js,mongodb,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').exe
UsersNotifications
.find({user_id: new ObjectId(req.user._id)})
.sort({'notifications.date': -1})
.select('notifications').exec().then(usersNotifications => {
res.locals.usersNotifications = usersNotifications;
});
以下是我的模型:
谢谢你的帮助 Afaik您不能按嵌套对象排序,但可以使用
通知
数组,应用降序排序并重新组合结果。比如:
.aggregate([
{ $match: { _id: new ObjectId(req.user._id) }},
{ $unwind: '$notifications' },
{ $sort: { 'notifications.date': -1 }},
{ $group: { _id: '$_id', notifications: { $push: '$notifications'}}}])
完美的它的工作如预期:)非常感谢你,很乐意帮助!:)