Search code examples
androidswiftfirebasefirebase-realtime-databasekey

Change keys in Firebase Realtime Database


I have an Android/iOS project that connects with a Realtime Database from Firebase.

For each user, the database saves some information by using the email of the user as the key.

As Firebase doesn't allow the keys to have ., the keys were settled to be the emails without .s (for example, the key for the user with email [email protected] is abc@gmailcom).

The issue may be clear now... because different users may have the same key.

The project requires the key to be the email (the UID is not useful in this case). So, I wanted to use the keys by changing the . for a ,.

The problem is that there are already some users using the app, and I don't want them to lose the information they already saved. I know that it could be fixed by hand:

  • take the list of emails of registered users
  • look up which key belongs to each email
  • add the , where needed.

Is there a way of doing this automatically?


Solution

  • There is no way to rename an existing node in the Realtime Database. In the other hand, it should be fairly straightforward to implement the three-step process you have outlined.

    1. Read the users,
    2. Loop over them.
    3. Write the data to its new location.
    4. Remove the data from its old location.

    If you want you can combine steps 3 and 4 with a single multi-location update, like Jay shows here. Setting the old location to null will delete it.

    So based on Jay's answer, something like this for each user:

    let usersRef = self.ref.child("user")
    
    messagesRef.updateChildValues([
      "email@with,com": { ... /* data of the user */ },
      "email@withcom": null
    ])