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

Firestore:如何使用DocumentReference指向其他项目的文档?

Can firebase.firestore.DocumentReference<T> point to documents in another Firebase project?

Absolutely! You can use DocumentReference<T> to target documents in a different Firebase project, and it works smoothly since Firebase fully supports working with multiple projects in a single app.

Here’s a step-by-step breakdown of how to make this work:

  • Initialize a secondary Firebase app instance
    First, set up a separate app instance for the target project. Pass the project’s unique configuration (apiKey, authDomain, projectId, etc.) and give the instance a distinct name to avoid conflicts with your default app:

    // Replace with your secondary project's actual config values
    const secondaryProjectConfig = {
      apiKey: "SECONDARY_PROJECT_API_KEY",
      authDomain: "secondary-project-id.firebaseapp.com",
      projectId: "secondary-project-id",
      // Include other required config fields like storageBucket, messagingSenderId, etc.
    };
    
    // Initialize the secondary app with a unique identifier
    const secondaryApp = firebase.initializeApp(secondaryProjectConfig, "secondary");
    
  • Retrieve the Firestore instance for the secondary project
    Once the secondary app is initialized, grab its associated Firestore instance:

    const secondaryFirestore = secondaryApp.firestore();
    
  • Create your cross-project DocumentReference
    Now you can generate a DocumentReference<T> exactly like you would for your primary project—this reference will point directly to a document in the secondary Firebase project:

    // Example: Reference a specific document in the secondary project's "posts" collection
    const crossProjectDocRef = secondaryFirestore.collection("posts").doc("summer-vacation-2024");
    

Key Considerations

  • Permissions are critical: Ensure the secondary project’s Firestore security rules allow your app to access the target documents. For backend code, you may need to use a service account with appropriate permissions for the secondary project.
  • Clean up unused instances: If you no longer need the secondary app instance, call secondaryApp.delete() to free up resources and prevent memory leaks.
  • Frontend checks: For web apps, confirm that the secondary project’s CORS settings don’t block requests from your primary app’s domain.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 14:12:49