0

I've been chasing my tail with this issue for a couple of days and It seems all the references I'm finding online are out of date and no longer relevant so I'd be very grateful of any suggestions.

I have a Firebase project with a realtime database and cloud functions that listen to this database and write back changes etc. I recently added a second database to the same project (closer to the user base) and this one is an identical copy of the first but I found that the cloud functions don't apply as expected. (Default DB is located in "us-central1" and second DB is located in "eurpoe-west1" if that makes any difference)

I found this topic referencing the same issue but none of the solutions work for me and some of the links referenced are no longer active so I can't view the examples. How to access multiple Realtime Database instances in Cloud Functions for Firebase

I can listen for changes at the second database no probs with the following example,

exports.exampleFunct = functions.region('europe-west1').database.instance('my_example-db-2').ref('/users/{uid}/requests/{request}').onCreate((req_snapshot, context) => {
        //Do stuff in here. It works so far...
});

The above works this far for the second database, however I haven't been able to read/write to the second database using the admin.database().ref().set() or admin.database().ref().once(...) .

For instance, If I wanted to load a users' entire node with this admin call inside the exampleFunct above.

admin.database().ref("users/" + uid).once("value", (user_snap) => {
    //Will only load default database.
});

This method above will only read the default database in my project, not the second database.

I have tried variations of the above function with my database URL, db name etc passed into the database() parameters as I have seen in some of the other solutions I found online but none worked for me. I also tried with and without the .europe-west1 reference in the url based on the suggestions from the errors in the cloud functions logs.

  • admin.database("my_example-db-2").ref();

  • admin.database().instance("my_example-db-2").ref();

  • admin.database("https://my_example-db-2.firebaseio.com").ref();

  • admin.database("https://my_example-db-2.europe-west1.firebasedatabase.app").ref();

  • admin.database("https://my_example-db-2.firebasedatabase.app").ref();

I also tried passing in the database url on initialisation as shown below.

admin.initializeApp({
    credential: admin.credential.applicationDefault(),
    databaseURL: 'https://my_example-db-2.europe-west1.firebaseio.com'//tried all variations of url.
});

And I also tried setting up a second instance like so,

const db2 = admin.initializeApp({
    databaseURL: "https://my_example-db-2.firebaseio.com"
}, 'db2');
...
admin.database(db2).ref();

But I have so far failed to be able to read/update the data on the second database.

Hopefully I haven't waffled on too much. My code has a lot of other baggage to it so I tried to simplify as much as I could and I'd be super grateful if anyone can give me some pointers on how I can read/write specifically to the second database. I feel like I'm missing something really obvious.

Thanks a mil.

##Update##

I have also tested the method suggested by Hiranya below with no success.

admin.initializeApp();

const defaultDb = admin.database();

// Get a reference to another DB in the same project.
const otherDb = admin.app().database('https://otherdb.firebaseio.com');

If I deploy the above suggestion using the url of my database https://my_example-db-2.firebasedatabase.app I will get an error on deployment saying,

Error: Error occurred while parsing your function triggers.

Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com

firebaseio.com isn't the domain of my database but If I try https://my_example-db-2.firebaseio.com instead it will deploy just fine but when I test the function and monitor the functions logs in the firebase console I see that it didn't read the second database and also gave this warning.

[2021-02-18T11:47:41.596Z]  @firebase/database: FIREBASE WARNING: 
Namespace my_example-db-2 lives in a different region. 
Please change your database URL to https://my_example-db-2.europe-west1.firebasedatabase.app (https://my_example-db-2.firebaseio.com)

I have tried all variations of the URL without success so It seems this solution won't work.

Spectre
  • 149
  • 1
  • 7

2 Answers2

1

If you're trying to write to the same database instance that triggered the event, you can get the root reference from the snapshot that is passed into the function:

exports.exampleFunct = functions.region('europe-west1').database
.instance('my_example-db-2')
.ref('/users/{uid}/requests/{request}')
.onCreate((req_snapshot, context) => {
  const rootRef = req_snapshot.ref.root;
  return rootRef.push("new value");
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks @Frank, (Big fan of your Firebase videos!) that looks like a tidy solution indeed, though I would like to be able to update both databases in a similar fashion If possible? as this would mean less modification of my existing code. I'll give your suggestion a try though. Thanks! :) – Spectre Feb 17 '21 at 18:37
  • 1
    This one I knew top of mind, but the other scenario definitely should also be possible. Hopefully somebody else knows the answer for that. – Frank van Puffelen Feb 17 '21 at 18:38
0

Have you tried something like this:

// Initialize with the default DB URL (fetched automatically in Cloud Functions)
admin.initializeApp();

const defaultDb = admin.database();

// Get a reference to another DB in the same project.
const otherDb = admin.app().database('https://otherdb.firebaseio.com');

See https://firebase.google.com/docs/reference/admin/node/admin.app.App-1#database

Hiranya Jayathilaka
  • 7,180
  • 1
  • 23
  • 34
  • That didn't work, unfortunately. I tried it with the ".firebaseio.com" domain and also the ".firebasedatabase.app" domain which is the actual url from my database. When deploying using the ".firebasedatabase.app" domain I get an error in the terminal, "Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://.firebaseio.com ". When I changed it to the ".firebaseio.com" domain it will deploy but the functions console logs throw a warning error and suggests changing the url back to the .firebasedatabase.app domain. – Spectre Feb 18 '21 at 11:54
  • You should always use the correct DB URL copied from the Firebase Console. I only used `firebaseio.com` as an example. However, if you're getting a URL parse error, you're either using an old version of the SDK, or you're running into a bug in the SDK. Try updating your dependencies first. If that doesn't help, file a bug report. – Hiranya Jayathilaka Feb 18 '21 at 18:04
  • Yeah an out dated version of the SDK was my first thought so I checked and updated everything and I'm on the latest already. I only tried the alternative URLs because they were suggested when trying to deploy and when monitoring the logs in the functions console so I tried both versions to see if I could narrow down the problem. – Spectre Feb 18 '21 at 23:16
  • Make sure you're using a recent version of `@firebase/database` package too. You might have to drop your package lock file and reinstall for everything to get updated. – Hiranya Jayathilaka Feb 19 '21 at 02:19