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

React交友应用无法从MongoDB获取匹配用户数据求助

交友应用匹配用户查询异常问题

问题描述

使用React开发交友应用时,能正常获取当前用户资料,但无法获取符合性别偏好的匹配用户。前端打印compatibleUsers始终为空数组[],但打印用户信息的日志正常输出。已检查MongoDB文档大小写,确认字段值格式正确。

MongoDB用户文档示例

{
  "_id":{"$oid":"660c165c29a4f35ac5ebf60d"},
  "user_id":"8c76db38-ba8d-46e1-a2c7-1f43e46d0d20",
  "email":"testing6@email.com",
  "hashed_password":"$2b$10$KhJOgnaYjsgWJC2vTHxTq.fGgVKtm.qxPuBYCphG7I1dPJOrziH/q",
  "about":"Explore another city",
  "date_of_birth":"1986-04-17T15:29:49.000Z",
  "full_name":"Bouchard",
  "gender_identity":"man",
  "gender_interest":"women",
  "matches":[]
}

前端代码(Dashboard.js)

// Fetch user profile.
const getUser = async () => {
  try {
    const response = await axios.get('http://localhost:8000/user', {
      params: {userId}
    })
    setUser(response.data);
    return;
  } catch(err) {
    console.log('A1', err)
  }
}
  
// Get compatible users of same interest.
const getCompatibleUsers = async () => {
  try {
    const response = await axios.get('http://localhost:8000/compatible-users', {
      params: { gender_identity: user?.gender_interest } 
    })
    console.log('Compatible Users Response:', response.data);
    setCompatibleUsers(response.data)
  }
  catch(err) {
    console.log('A2', err)
  } 
}

useEffect(() => {
  getUser();
}, [userId]);

useEffect(() => {
  if (user && !compatibleUsers) {
    getCompatibleUsers();
  }
}, [user]);

console.log('User:', user)
console.log('Compatible Users:', compatibleUsers)

后端代码(Server: index.js)

// Fetch individual user.
app.get("/user", async (req, res) => {
  const client = new MongoClient(uri);
  const userId = req.query.userId 

  console.log('userId:', userId) // Delete when done testing.

  try {
    const client = new MongoClient(uri);
    await client.connect();
    const database = client.db("app-data");
    const users = database.collection("users");

    const query = { user_id: userId }
    const user = await users.findOne(query)
    res.send(user)
    return;
  } catch (error) {
    console.error('B3', error);
  } finally {
    await client.close()
  }
});

// Fetch compatible users.
app.get("/compatible-users", async (req, res) => {
  const client = new MongoClient(uri);
  const genderIdentity = req.query.gender_identity;

  console.log('Interest: ', genderIdentity) // Delete when done testing.

  try {
    await client.connect();
    const database = client.db("app-data");
    const users = database.collection("users");
    const query = { gender_identity: { $eq: genderIdentity } }; 
    const foundUsers = await users.find(query).toArray();

    console.log('Found Users:', foundUsers);

    res.send(foundUsers);
  } catch (err) {
    console.error('B4', err);
  } finally {
    await client.close();
  }
});

排查情况

已添加多个console.log,仅前端用户信息日志、后端Interest:日志正常输出,compatibleUsers和Found Users:日志均显示为空数组。


问题根源及解决方法

1. 前端useEffect触发条件错误

当前第二个useEffect的判断条件是if (user && !compatibleUsers),但compatibleUsers初始值为空数组[],!compatibleUsers结果为false,导致getCompatibleUsers永远不会执行。

修复代码:

useEffect(() => {
  if (user && compatibleUsers.length === 0) {
    getCompatibleUsers();
  }
}, [user, compatibleUsers]);
  • 将判断条件改为compatibleUsers.length === 0,确保用户数据加载完成且匹配用户未获取时触发查询。
  • 依赖项添加compatibleUsers,避免重复触发或遗漏更新。

2. 后端查询未排除当前用户

当前后端查询会将当前用户也包含在结果中,需要过滤掉当前用户的user_id。

修复步骤:

  1. 前端传递当前用户ID到后端:
// 前端getCompatibleUsers修改参数
const response = await axios.get('http://localhost:8000/compatible-users', {
  params: { 
    gender_identity: user?.gender_interest,
    currentUserId: user.user_id // 新增当前用户ID参数
  } 
})
  1. 后端修改查询条件:
// 后端/compatible-users接口修改
const genderIdentity = req.query.gender_identity;
const currentUserId = req.query.currentUserId;

// ...

const query = { 
  gender_identity: { $eq: genderIdentity },
  user_id: { $ne: currentUserId } // 排除当前用户
}; 

3. 验证数据库中是否存在符合条件的用户

直接在MongoDB Compass中执行查询,确认app-data库的users集合中是否有匹配用户:

db.users.find({ gender_identity: "women" })

如果查询结果为空,说明没有符合条件的用户,需要添加测试数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:13:25