如何使用Mongoose对嵌套对象数组中的对象数组内容排序
用MongoDB/Mongoose对嵌套数组hobbies按指定字段排序的正确实现
你的代码问题在于:findOne返回的是Mongoose文档(或普通JS对象),此时访问.hobbies已经是内存中的JavaScript数组,后续调用的.sort()是JS原生数组的排序方法,并非MongoDB内置的排序逻辑,不符合你的需求。
要在数据库层面完成嵌套数组的排序,推荐使用以下两种方案:
方案一:使用$sortArray(MongoDB 5.2及以上版本)
$sortArray是MongoDB专门用于数组排序的聚合操作符,语法简洁高效:
async function findPlaceSort(username, sortElement, sortDirection) { const aggregatedResult = await User.aggregate([ // 匹配目标用户 { $match: { username: username } }, // 投影并排序hobbies数组 { $project: { hobbies: { $sortArray: { input: "$hobbies", sortBy: { [sortElement]: sortDirection } } }, _id: 0 // 不需要返回_id字段 } } ]); // 聚合返回数组,取第一个结果的hobbies(如果存在) return aggregatedResult.length > 0 ? aggregatedResult[0].hobbies : []; }
方案二:兼容低版本MongoDB(5.2以下)
如果你的MongoDB版本不支持$sortArray,可以用$unwind+$sort+$group的组合实现:
async function findPlaceSort(username, sortElement, sortDirection) { const aggregatedResult = await User.aggregate([ { $match: { username: username } }, { $unwind: "$hobbies" }, // 将hobbies数组拆分为单个文档 { $sort: { [`hobbies.${sortElement}`]: sortDirection } }, // 按指定字段排序 { $group: { _id: "$_id", hobbies: { $push: "$hobbies" } // 将排序后的文档重新组合为数组 } }, { $project: { hobbies: 1, _id: 0 } } // 只返回hobbies字段 ]); return aggregatedResult.length > 0 ? aggregatedResult[0].hobbies : []; }
调用方式和你之前一致:findPlaceSort('Alice', 'place', 1),就能得到按place升序排列的Alice的hobbies数组。
内容的提问来源于stack exchange,提问作者Nico
相关产品推荐
相关产品推荐

