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

Firestore查询:获取好友列表含指定UID的用户UID列表

问题说明

Users集合数据结构

每个用户文档包含以下字段:

  • firstName:用户名字
  • lastName:用户姓氏
  • uid:用户唯一ID
  • grade:用户年级
  • friends:数组类型,存储好友的文档引用路径,示例格式:["users/1", "users/2"]

需求

获取所有friends数组中包含UID为1的用户的UID列表。

当前尝试的代码(存在问题)

String userid="1";
const userRef = admin.firestore().collection('users').doc(userid).get();
var friends = await users
      .where('friends', 'array-contains', userRef)
      .limit(3)
      .get();

问题排查

  1. doc(userid).get()是异步操作,返回的是Promise对象,不是文档引用,直接用来做array-contains匹配会失败。
  2. 你的friends数组存储的是文档路径字符串(如"users/1"),但代码里用了Promise对象去匹配,类型不匹配导致查询无结果。

正确实现代码

方案一:匹配路径字符串(对应现有数据结构)

直接构造目标好友的文档路径字符串进行查询:

const userId = "1";
const targetFriendPath = `users/${userId}`;

const querySnapshot = await admin.firestore()
  .collection('users')
  .where('friends', 'array-contains', targetFriendPath)
  .limit(3)
  .get();

// 提取符合条件的用户UID列表
const userUidList = querySnapshot.docs.map(doc => doc.data().uid);

方案二:匹配文档引用(若调整存储结构)

如果后续将friends改为存储文档引用对象,可使用以下代码:

const userId = "1";
// 获取文档引用,不要加.get()
const targetFriendRef = admin.firestore().collection('users').doc(userId);

const querySnapshot = await admin.firestore()
  .collection('users')
  .where('friends', 'array-contains', targetFriendRef)
  .limit(3)
  .get();

const userUidList = querySnapshot.docs.map(doc => doc.data().uid);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 01:27:11