Search code examples
c#firebaseunity-game-enginefirebase-realtime-database

What is the best way to check if a Firebase Database child already exists, and add it if it doesn't?


I am using Firebase Realtime Database (not Firestore) with Unity and C#. My database has the following structure:

asdfghjkl
   Lance Armstrong: 30
qwertyuiop
   Bob Dylan: 45
zxcvbnm
   Googoo Gaga: 29

I want to see if a certain top-level child exists, and if it doesn't I want to create it. Otherwise, I want to update it.
For example, I'd like to know if asdfghjkl exists in the database and if it does, update the Value of Lance Armstrong to 32. If it doesn't, I want to create it and have Lance Armstrong: 32 under it. What is the best way of doing this?

I've tried

FirebaseDatabase.DefaultInstance.GetReference("asdfghjkl").GetValueAsync()

but when there is no entry asdfghjkl, this code doesn't automatically create it. How can I do this? Is there a way I can read and write in one go?


Solution

  • The best way with Firebase (and most databases) is to look for a so-called idempotent write operation, as they scale the best. In your case, that leads to the question: how about always writing value 32 to path asdfghjkl/Lance Armstrong? That way you don't need to check if the node exists first.

    This works on Firebase, because ancestor nodes are automatically created when you write a value under them (so both asdfghjkl and Lance Armstrong are auto-created if they don't exist). Ancestor nodes are also automatically deleted when there no longer is any value under them btw, which means that in most cases you don't have to think about them.


    If the value you write depends on the value in the database, then the above won't necessarily apply. In such cases you will need to use a transaction.