Best way to add data to a list in firebase database

Viewed 101

I am using Firebase realtime database and was trying to store a list of "Animales" for a user.

Database structure:

Database structure link

What I want to achieve is that for example: for the user with "Uuid" 11111 a list with the animals that he is publishing appears. I mean:

Fireabase-root
    |
    --- 11111
          |
          --- animal1 
                |
                --- descripcion: "algo"
                |
                --- edad: "algo"
                |
                --- nombre: "algo"
                |
                --- raza: "algo"

           --- animal2
               ...
           --- animal3
               ...

I wanted to know what is the best way to do this. I thought that the child "animal1" is a key and for each animal that is generated a different key is added, but I don't know if this is the best way to solve it. I tried to try with the push method that I saw that generates a key, but I don't know how to use it. I leave what I was testing.

DatabaseReference nombre = FirebaseDatabase.getInstance().getReference().child("Users").child("Animales").child(userId).push().child("nombre");
nombre.setValue("Leon");
1 Answers

If the number of Animals you have compared to the number of users is smaller, then what you can do is, under the root-node, form a node called Animals, and whenever a new animal is created you add it there.

Again under the root-node form a child-node called users, and inside that you add user1,user2, etc... Now each time a user is associated with an animal you create a new child-node under that user and add just the name of the animal from the Animals node. When you need to access the properties of those animals just refer to their information from Animals.

This makes the tree way shorter, and I think it is a more elegant way of doing it, instead of creating the same animal repeatedly for different users.

Related