为何获取推荐关注用户接口仍返回含自身ID的followers数组用户?
解决Mongoose查询未关注用户的逻辑错误
你当前的查询逻辑完全搞反了——你要找的是当前用户未关注的用户,但写的条件followers: { $nin: [id] }实际是在筛选“没关注当前用户的用户”,而非“当前用户没关注的用户”。这就是为什么原查询返回不符合预期的结果,换成$in又返回空数组(大概率是当前用户还没被其他用户关注)。
修正后的控制器代码
export const getWhoToFollow = catchAsync( async (req: Request & AuthRequest, res: Response, next: NextFunction) => { const currentUserId = new mongoose.Types.ObjectId(req.userData?.id); // 先获取当前用户已关注的ID列表 const currentUser = await User.findById(currentUserId).select('following'); const followingIds = currentUser?.following || []; // 查询未关注的用户:排除自己,且ID不在已关注列表中 const users = await User.find({ _id: { $ne: currentUserId, $nin: followingIds } }).limit(3); res.status(200).json(users); } );
逻辑说明
- 先通过
findById获取当前用户的following数组,这是当前用户已经关注的所有用户ID集合。 - 查询条件改为
_id不等于当前用户ID,并且不在followingIds数组中,这样就能精准筛选出当前用户未关注的用户。
可选:聚合查询版本(减少一次数据库请求)
export const getWhoToFollow = catchAsync( async (req: Request & AuthRequest, res: Response, next: NextFunction) => { const currentUserId = new mongoose.Types.ObjectId(req.userData?.id); const users = await User.aggregate([ // 排除当前用户自身 { $match: { _id: { $ne: currentUserId } } }, // 关联当前用户的关注列表,判断该用户是否已被关注 { $lookup: { from: 'users', pipeline: [ { $match: { _id: currentUserId } }, { $project: { _id: 0, following: 1 } } ], as: 'currentUser' } }, // 展开当前用户数据 { $unwind: '$currentUser' }, // 筛选未被当前用户关注的用户 { $match: { $expr: { $not: { $in: ['$_id', '$currentUser.following'] } } } }, // 限制返回数量 { $limit: 3 }, // 移除临时字段 { $project: { currentUser: 0 } } ]); res.status(200).json(users); } );
内容的提问来源于stack exchange,提问作者Mario Podolinský
相关产品推荐
相关产品推荐

