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

Firestore关联查询:如何获取UserID1的好友及其姓名

How to Fetch UserID1's Friends and Their Names from Firestore

Hey there! Let's work through how to pull userID1's friends and their corresponding names from your Firestore database. First, I want to flag a small issue with your current Friends collection structure—you can't have two documents with the same ID (userID1) in the same collection (Firestore enforces unique document IDs per collection). Let's adjust that to a more scalable, standard setup first, then walk through the query logic.


Instead of creating duplicate documents for the same user, store all friend IDs in an array field within a single document for each user. Here's the revised structure:

Users (collection)

userID1 (document)

name: "Alice" (field)
age: 30 (field)
userID2 (document)
name: "Bob" (field)
age: 28 (field)
userID3 (document)
name: "Charlie" (field)
age: 32 (field)

Friends (collection)

userID1 (document)

friendIDs: ["userID2", "userID3"] (array field)

This structure makes it easier to manage friends (add/remove entries) and avoids duplicate document conflicts.


Step 2: Write the Query Logic (Firebase v9 Modular Syntax)

We'll split this into two parts: first fetching the list of friend IDs, then fetching the corresponding user names.

Part 1: Get the List of Friend IDs for userID1

This function retrieves the array of friend IDs from the Friends collection:

import { doc, getDoc } from "firebase/firestore";
import { db } from "./firebase-config"; // Import your initialized Firestore instance

async function getUserFriendIDs(userId) {
  const friendDocRef = doc(db, "Friends", userId);
  const friendDocSnap = await getDoc(friendDocRef);

  if (friendDocSnap.exists()) {
    // Return the array of friend IDs from the optimized structure
    return friendDocSnap.data().friendIDs;
    // If you're sticking with your original (non-recommended) structure, use this instead:
    // return Object.values(friendDocSnap.data()); // Extracts all field values (friend IDs)
  } else {
    console.log(`No friend document found for user ${userId}`);
    return [];
  }
}

Part 2: Fetch Friend Names Using the ID List

Once we have the friend IDs, we use a where-in query to fetch all matching user documents from the Users collection:

import { getDocs, query, where, collection } from "firebase/firestore";

async function getFriendNames(friendIDs) {
  if (friendIDs.length === 0) return [];

  const usersCollection = collection(db, "Users");
  // Use "__name__" to query against document IDs
  const friendQuery = query(usersCollection, where("__name__", "in", friendIDs));

  const querySnapshot = await getDocs(friendQuery);
  const friendDetails = [];

  querySnapshot.forEach((doc) => {
    friendDetails.push({
      userId: doc.id,
      name: doc.data().name
    });
  });

  return friendDetails;
}

Part 3: Combine the Functions

Call both functions together to get the final list of friends with names:

async function getUserFriendsWithNames(userId) {
  const friendIDs = await getUserFriendIDs(userId);
  const friendsWithNames = await getFriendNames(friendIDs);
  console.log(`Friends of ${userId}:`, friendsWithNames);
  return friendsWithNames;
}

// Run the function for userID1
getUserFriendsWithNames("userID1");

Important Notes

  • Where-In Query Limit: Firestore restricts where-in queries to a maximum of 10 values. If your user has more than 10 friends, split the friendIDs array into chunks of 10, run multiple queries, and combine the results.
  • Security Rules: Ensure your Firestore security rules allow read access to both the Friends and Users collections for the authenticated user.
  • Original Structure Caveats: If you keep your original Friends structure (with duplicate documents), you'll run into document ID conflicts. You'd need to use a different identifier for each document (e.g., auto-generated IDs) and add a userId field to filter by, but this is far less efficient than the array approach.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:39:56