user8890895
user8890895

Reputation:

How to rename the keys in Firebase Storage and Database

I am using Firebase storage to upload some photos as 1,2,3 etc. I then use Firebase Database to save the download URL for those photos in the same manner. I was wondering how should I deal with the files once I delete one of the images in between. For instance, let's say I delete image 2 and there are 7 images. How should I rename the keys for 3,4,5,6,7 and make them 2,3,4,5,6 ?!

Upvotes: 0

Views: 1172

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598901

The best advice is to not use such sequential numbers, since they don't scale very well. Your current question is one of the many problems with it. For more, see https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html.

The recommended approach is to use a Firebase Database push ID to name/identify the files. You can easily get this with ref.push().key or ref.push().getKey(). These IDs are always-incrementing, but not sequential. While slightly less readable, they scale better, can be generated why you're offline, and you don't have to regenerate the other IDs when you remove a file/node.

Also see Mike's answer here: Creating a new unique path to Firebase Storage, coupled with storing it in the database?

Upvotes: 1

cutiko
cutiko

Reputation: 10517

Firebase Functions onDelete for the RTD

https://firebase.google.com/docs/functions/database-events?hl=es-419

Don't allow user to delete in storage but allow them.to delete the reference in the RTD. Then Functions will take care of backend logic.

Please make sure your data structure is correct, that sounds like an array and you should allow push keys, use a Map instead

Upvotes: 0

Related Questions