Firestore:如何使用DocumentReference指向其他项目的文档?
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 aDocumentReference<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

