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

在Express.js+MongoDB中筛选指定用户的已通过好友列表

解决方案

方法1:使用findOne配合$filter投影

直接在查询时通过投影操作符$filter筛选出friends数组中approved: true的元素,简洁高效,适合仅需获取目标用户过滤后好友列表的场景。

示例代码:

const User = require('./models/User'); // 引入你的User模型

async function getApprovedFriends(userEmail) {
  const user = await User.findOne(
    { email: userEmail }, // 根据邮箱定位用户
    {
      friends: {
        $filter: {
          input: '$friends',
          as: 'friend',
          cond: { $eq: ['$$friend.approved', true] }
        }
      },
      _id: 0 // 可选,不需要返回_id则添加
    }
  );
  return user?.friends || [];
}

方法2:使用聚合管道

如果需要后续复杂数据处理(比如统计好友数、关联其他集合等),聚合管道会更灵活:

示例代码:

async function getApprovedFriends(userEmail) {
  const result = await User.aggregate([
    { $match: { email: userEmail } }, // 第一步:定位目标用户
    {
      $addFields: {
        // 替换原friends数组为过滤后的结果
        friends: {
          $filter: {
            input: '$friends',
            as: 'friend',
            cond: { $eq: ['$$friend.approved', true] }
          }
        }
      }
    },
    { $project: { _id: 0 } } // 可选,按需控制返回字段
  ]);
  return result[0]?.friends || [];
}

关键说明

  • $filter是MongoDB数组操作符,用于遍历数组并按条件筛选元素,$$friend为管道变量,代表当前遍历的好友对象。
  • 如果原接口返回整个用户文档,只需把上述筛选逻辑整合到原查询代码中,替换原返回全部friends的逻辑即可。

内容的提问来源于stack exchange,提问作者Ahmed hussien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 00:45:04