You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 the Connections collection 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 userAId and userBId are valid Mongoose ObjectIds. If you’re passing string IDs, convert them first with mongoose.Types.ObjectId(userId).
  • Both methods are performant, but the count check is more concise for straightforward mutual follow checks.

内容的提问来源于stack exchange,提问作者a duck

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:03:39