3

I want to listen to two databases in my google cloud functions so I tried this

 const app1 = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://honey.firebaseio.com"
});

const app2 = admin.initializeApp({
   credential: admin.credential.cert(serviceAccount),
   databaseURL: "https://honey-d8.firebaseio.com/"
}, 'app2'); 




// Get the default database instance for an app1
var OperationDB = admin.database().ref();

// Get a database instance for app2
var userDB = admin.database(app2).ref();

then I tried to call the second database

 exports.onBoardNewUser = functions.userDB.ref('/Users/').onCreate((snapshot, context) => {

 })

whenever I attempt to deploy the file it gives this error

Cannot read property 'ref' of undefined

The two databases are in the same project

I have tried different variations but no luck. what am I doing wrong an how can I fix this ?

e.iluf
  • 1,145
  • 2
  • 18
  • 34

1 Answers1

4

You can't attach a Cloud Function to some arbitrary database reference. Cloud Functions database triggers are not like listeners that you get with the client SDKs. It receives events from Realtime Database as they are generated.

You have to use the provided API to build a function that references a particular database and path to receive updates.

You can't reference a database outside of the project where you deployed the function.

You can reference multiple shards of a database within the same project. To do that, you have to specify the name of the shard instance using the provided API. If you don't name the instance in the function builder using the instance() method, you will only receive events from the primary/default shard.

If you want to handle events for all of your shards at the same location in each one, you have to export one function for each shard, and they can each delegate to the same helper function to handle the event.

Doug Stevenson
  • 236,239
  • 27
  • 275
  • 302
  • The two databases are in the same project – e.iluf Dec 20 '18 at 23:02
  • Then use the provided API that I linked to in order to receive events from your two instances. https://firebase.google.com/docs/functions/database-events#specify_the_database_instance_and_path – Doug Stevenson Dec 20 '18 at 23:18
  • It works for just one database. The code I posted is my attempt to initialize the second database. I'm not sure I'm initializing it and call it rightly. The API example is for one database – e.iluf Dec 21 '18 at 02:21
  • 1
    The link I gave you explains how to use multiple shards. You will use the instance() method on the function builder to specify the name of the shard. https://firebase.google.com/docs/functions/database-events#specify_the_database_instance_and_path – Doug Stevenson Dec 21 '18 at 02:39