Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting custom key when pushing new data to firebase database

Well, I am new to Firebase and I want to have my own keys while pushing new data to database.

Problem:

FireBase.push().setValue(mapped_values);

This gives structure like below:

 database output

How can I create my own custom key there? Such as username or something.

like image 808
Victor Davis Lenz Avatar asked May 27 '16 12:05

Victor Davis Lenz


7 Answers

Calling push() will generate a key for you.

If instead you use child(), you can determine they key/path yourself.

ref.child("Victor").setValue("setting custom key when pushing new data to firebase database");
like image 136
Frank van Puffelen Avatar answered Oct 05 '22 18:10

Frank van Puffelen


        String key="1234567sdfsf8";
        //custom object
        User user=new User();
        DatabaseReference mDatabase;
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("Users").child(key).setValue(user);
like image 28
iqbal lone Avatar answered Oct 05 '22 18:10

iqbal lone


As an update to the top answer, the Firebase API has been changed and setValue() does not work anymore. Now you must use the set() function instead:

ref.child("Victor").set("setting custom key when pushing new data to firebase database");
like image 22
Alberto Avatar answered Oct 05 '22 18:10

Alberto


You can create a custom key using setValue() even if the root contains many children for example if 'Users' is the root and you want to add users with email as a key it will be like this

firebase.child("firebase url").child("Users").child("user_1 email").setValue(...)

firebase.child("firebase url").child("Users").child("user_2 email").setValue(...)

etc

like image 38
Rand Avatar answered Oct 05 '22 18:10

Rand


let's say your db look like

 "BookShelf" : {
    "book1" : {
      "bookName" : "book1_push"
       ...
     }

your code to be (don't use push(), push() generate a random key)

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
Book data = new Book();
mDatabase.child("BookShelf").child("book1").setValue(data);
    
     
like image 41
Energy Avatar answered Oct 05 '22 18:10

Energy


If you are using FirebaseUI :

private static final CollectionReference usersCollection = FirebaseFirestore.getInstance().collection("users");

User user = new User("MyUsername", "MyPictureUrl");
String userKey = "1234567sdfsf8";

usersCollection.document(userKey).set(user); //MAGIC LINE
like image 23
Phil Avatar answered Oct 05 '22 19:10

Phil


In POST request it will generate ID's but in PATCH, PUT request it will mention the key which will be provided by you.

like image 28
pramod singh Avatar answered Oct 05 '22 20:10

pramod singh