3
votes

How can I use Cloud Functions for Firebase database triggers to edit/update existing data?

My Use Case: I have existing data in my Firebase database, say a/{uid}/b, at the time of writing, I have 14-15 uids in the db where b is already defined. Now I want to use cloud function to listen to write to b and add some more data based on that.

The database trigger functions.database.ref('/a/{uid}/b').onWrite will only execute for new writes/updates to the specific path, not for existing writes/updates.

How can Cloud Functions for Firebase help when I want to update all the data at once for existing write logics?

1
I'd create a separate function (HTTP or Database triggered, doesn't really matter) purely for the migration. Then again: you could also simply do that with a local node script.Frank van Puffelen

1 Answers

0
votes

I had a similar situation. I found a workaround to get the function executed. This is not ideal for production database but worked for me for a small database.

Export existing data from a collection ( or entire database ) into a file on which you have trigger functions.

Then delete the data that is exported from the database. ( Please be aware if you have onWrite function, it gets executed on delete as well. Make sure code handles it properly )

Command to export a collection

firestore-export --accountCredentials=/path/credentials.json --nodePath collectionName

Then import the backup data in the same collection using the command below.

firestore-import --accountCredentials=/path/credentials.json --backupFile /path/backupFilename.json --nodePath collectionName

More information about firebase-export npm package @ https://www.npmjs.com/package/node-firestore-import-export