0

I have multiple database instances in my firebase app. I am trying to write into three database instances in firebase cloud functions. My understanding by following this document is no need to initialize multiple apps for each database instance. We can initialize one and pass in the database url. As a side note, I have another function with similar kind of functionality where I have trigger event in one database and write data to other database instance and it works fine.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
const app = admin.app();

export const onStart = 
functions.database.instance('my-db-1')
        .ref('path')
        .onCreate(async (snapshot, context) => {
    return await onCreate('my-db-1',snapshot,context);
        });
 export const onStartDb01 = functions.database.instance('my-db-2')
        .ref('path')
        .onCreate(async (snapshot, context) => {
            return await onCreate('my-db-2', snapshot, context);
        });

async function onCreate(dbInstance: string, snapshot: 
functions.database.DataSnapshot, context: functions.EventContext): 
Promise<any> {
    const defaultDb = app.database(defaultDbUrl);
    const actvDb = app.database(actvDbUrl);

    await defaultDb.ref('path')
        .once("value")
        .then(snap => {
        const val = snap.val();
         ---do something and write back---
       });
    await actvDb.ref('path')
        .once("value")
        .then(snap => {
        const val = snap.val();
        ---do something and write back---
    });
    return true;    
 }

But when a db event is fired, it logs the error as below

Error: FIREBASE FATAL ERROR: Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.

Giri
  • 451
  • 1
  • 4
  • 13
  • Please edit the question to show the **entire** code that doesn't work the way you expect. Especially how you initialize each variable. The question should have enough information so that anyone can reproduce the issue. – Doug Stevenson Aug 27 '20 at 18:54
  • It still doesn't look complete to me. What exactly are `defaultDbInstance` and `secondDb`? They have no assignments here. – Doug Stevenson Aug 27 '20 at 19:49
  • @DougStevenson They are the database names. – Giri Aug 27 '20 at 20:01

1 Answers1

2

You'll need to initialize a separate app() for each database instance.

Based on Doug's answer here that should be something like this:

const app1 = admin.initializeApp(functions.config().firebase)
const app2 = admin.initializeApp(functions.config().firebase)

And then:

const defaultDb = app1.database(defaultDbUrl);
const actvDb = app2.database(actvDbUrl);
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807