如何用Mongoose聚合查询判断两个用户是否互相关注?
Checking Mutual Follow Status with Mongoose Aggregation
Hey there, let's work through how to check if two users are following each other using Mongoose. Given your setup where the Connections collection tracks follow relationships (idA is the follower, idB is the followed user), here are two straightforward, effective approaches:
Approach 1: Aggregation Pipeline (Flexible for Future Extensions)
This method uses MongoDB's aggregation framework to directly return a boolean indicating mutual follow status, and it’s easy to expand if you need to add more logic later.
const checkMutualFollow = async (userAId, userBId) => { const mutualCheckResult = await Connection.aggregate([ // Step 1: Match both possible follow direction records { $match: { $or: [ { idA: userAId, idB: userBId }, { idA: userBId, idB: userAId } ] } }, // Step 2: Count how many valid relationship records exist { $group: { _id: null, relationshipCount: { $sum: 1 } } }, // Step 3: Convert the count to a clear mutual status boolean { $project: { _id: 0, isMutual: { $eq: ["$relationshipCount", 2] } } } ]); // If no results come back, at least one follow relationship is missing return mutualCheckResult.length > 0 ? mutualCheckResult[0].isMutual : false; };
Breakdown:
$match: Filters theConnectionscollection to find any documents where either userA follows userB, or userB follows userA.$group: Counts how many matching documents exist. For a mutual follow, this count will be exactly 2.$project: Transforms the count into a readable boolean (isMutual) that tells us if both relationships exist.
Approach 2: Simplified Count Check (Concise for Basic Use Cases)
If you don’t need the flexibility of an aggregation pipeline, a simpler countDocuments call gets the job done just as efficiently:
const checkMutualFollow = async (userAId, userBId) => { const relationshipCount = await Connection.countDocuments({ $or: [ { idA: userAId, idB: userBId }, { idA: userBId, idB: userAId } ] }); // Exactly 2 documents means both users follow each other return relationshipCount === 2; };
Quick Notes:
- Ensure
userAIdanduserBIdare valid MongooseObjectIds. If you’re passing string IDs, convert them first withmongoose.Types.ObjectId(userId). - Both methods are performant, but the count check is more concise for straightforward mutual follow checks.
内容的提问来源于stack exchange,提问作者a duck
相关产品推荐
相关产品推荐

