Mongoose中如何通过关联User的所属部门查询对应Ticket工单列表
问题原因
你原来的写法无法生效,核心原因是Ticket集合中的author字段仅存储关联User文档的ObjectId,不存在内嵌的author.department属性,无法直接在find的查询条件中通过该字段过滤工单。
正确实现方案
方案1:二次查询法(简单易读,适合中小数据量场景)
先查询目标部门下的所有用户ID,再用ID列表过滤工单:
// 1. 查询指定部门的所有用户ID const deptUserIds = await User.find({ department: req.user.department }).distinct('_id'); // 2. 查询对应用户提交的所有工单 const deptTickets = await Ticket.find({ author: { $in: deptUserIds } }).populate('author');
方案2:聚合关联查询(单步查询,适合大数据量场景)
使用MongoDB的$lookup聚合算子直接关联User表过滤:
const deptTickets = await Ticket.aggregate([ // 关联User集合,匹配author对应的用户数据 { $lookup: { from: 'users', // 对应MongoDB中User模型的实际集合名,默认是模型名小写加s localField: 'author', foreignField: '_id', as: 'author' } }, // 展开关联得到的数组(1对1关联后数组仅1条数据) { $unwind: '$author' }, // 匹配部门条件,注意要将字符串ID转为ObjectId类型 { $match: { 'author.department': mongoose.Types.ObjectId(req.user.department) } } ])
如果需要保持和普通populate查询一致的实例方法,可以在聚合后调用Ticket.populate(deptTickets, { path: 'author.department' })关联部门信息。
内容的提问来源于stack exchange,提问作者buga
相关产品推荐
相关产品推荐

