Firestore查询:获取好友列表含指定UID的用户UID列表
问题说明
Users集合数据结构
每个用户文档包含以下字段:
firstName:用户名字lastName:用户姓氏uid:用户唯一IDgrade:用户年级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();
问题排查
doc(userid).get()是异步操作,返回的是Promise对象,不是文档引用,直接用来做array-contains匹配会失败。- 你的
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
相关产品推荐
相关产品推荐

