Hari Karthyk
Hari Karthyk

Reputation: 21

How to Switch Between Multiple Firestore Databases in the same firebase app

My Firebase project contains multiple Firestore databases, and I need to switch between these databases in my code.

const response = await firestore().collection(collectionId).doc(savedId).get().then((doc: any) => {
   console.log(doc.data(), 'doc.data()');
   return doc.data();
});

This connects to the default database, but how to mention the database Id ?

I have tried to create another app instance, but even though I am not able to find any documents or articles related to switching multiple database IDs for the Firestore in react native.

In node js, I am able to switch between different databaseId within the same project.

const { Firestore } = require('@google-cloud/firestore');

var firestore = new Firestore({          
   projectId: projectId,          
   databaseId: databaseId,          
   keyFilename: keyFilenamePath
});

Upvotes: 2

Views: 267

Answers (2)

mondieki
mondieki

Reputation: 1971

To switch between multiple Firestore databases in the same Firebase app, you can set the database ID when instantiating the Firestore client.

Each Firestore database is identified by a unique database ID, which defaults to (default) if unspecified.

Here’s how you can do it for a database named "prod-db":

import { getFirestore } from "firebase/firestore";

// or how your firebase library imports it, eg
// import { getFirestore } from '@angular/fire/firestore';

// Then, initialize Cloud Firestore and get a reference to the "prod-db" Firestore database
const db = getFirestore("prod-db");

Replace "prod-db" with the ID of your desired database.

Be sure to update to the latest Firebase Client SDKs and Google API Client Libraries.

Upvotes: 0

Darlington
Darlington

Reputation: 61

  1. Install Firebase Dependencies:

First, ensure you have the Firebase dependencies installed in your React Native project:

npm install @react-native-firebase/app @react-native-firebase/firestore
  1. Configure Multiple Firebase Apps:

In your Firebase project, create different configurations for each Firestore database you want to use. Each configuration should include apiKey, authDomain, projectId, storageBucket, messagingSenderId, and appId.

  1. Initialize Multiple Firebase Apps:

Initialize multiple Firebase app instances with their respective configurations.

import firebase from '@react-native-firebase/app';
import '@react-native-firebase/firestore';

const firebaseConfig1 = {
  apiKey: 'YOUR_API_KEY_1',
  authDomain: 'YOUR_AUTH_DOMAIN_1',
  projectId: 'YOUR_PROJECT_ID_1',
  storageBucket: 'YOUR_STORAGE_BUCKET_1',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID_1',
  appId: 'YOUR_APP_ID_1',
};

const firebaseConfig2 = {
  apiKey: 'YOUR_API_KEY_2',
  authDomain: 'YOUR_AUTH_DOMAIN_2',
  projectId: 'YOUR_PROJECT_ID_2',
  storageBucket: 'YOUR_STORAGE_BUCKET_2',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID_2',
  appId: 'YOUR_APP_ID_2',
};

// Initialize the default app
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig1);
}

// Initialize secondary app
const secondaryApp = firebase.initializeApp(firebaseConfig2, 'secondary');
  1. Access Firestore Instances:

Access Firestore instances from each app instance.

const firestoreDefault = firebase.firestore();
const firestoreSecondary = secondaryApp.firestore();
  1. Switch Between Firestore Databases:

Use the respective Firestore instance depending on which database you need to access.

const useDefaultDatabase = true; // Change this flag to switch databases

const firestore = useDefaultDatabase ? firestoreDefault : firestoreSecondary;

// Example usage
firestore.collection('your-collection').get()
  .then(querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
      console.log(documentSnapshot.data());
    });
  });

Example Component Here's an example component that demonstrates switching between two Firestore databases:

import React, { useState } from 'react';
import { View, Button, Text } from 'react-native';
import firebase from '@react-native-firebase/app';
import '@react-native-firebase/firestore';

const firebaseConfig1 = {
  // Your first Firebase configuration
};

const firebaseConfig2 = {
  // Your second Firebase configuration
};

// Initialize the default app
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig1);
}

// Initialize secondary app
const secondaryApp = firebase.initializeApp(firebaseConfig2, 'secondary');

// Firestore instances
const firestoreDefault = firebase.firestore();
const firestoreSecondary = secondaryApp.firestore();

const FirestoreSwitcher = () => {
  const [useDefaultDatabase, setUseDefaultDatabase] = useState(true);
  const firestore = useDefaultDatabase ? firestoreDefault : firestoreSecondary;

  const fetchData = async () => {
    const snapshot = await firestore.collection('your-collection').get();
    snapshot.forEach(doc => {
      console.log(doc.data());
    });
  };

  return (
    <View>
      <Button title="Switch Database" onPress={() => setUseDefaultDatabase(!useDefaultDatabase)} />
      <Button title="Fetch Data" onPress={fetchData} />
    </View>
  );
};

export default FirestoreSwitcher;

Upvotes: 0

Related Questions