Setting custom key when pushing new data to firebase database

后端 未结 10 572
野的像风
野的像风 2020-12-13 12:22

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);


        
相关标签:
10条回答
  • 2020-12-13 13:19

    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);
        
         
    
    0 讨论(0)
  • 2020-12-13 13:20

    Just for sharing the knowledge.

    if you are using fire-sharp, you can create the custom key as follows

                IFirebaseConfig config = new FirebaseConfig
                {
                    AuthSecret = "SecretKey",
                    BasePath = "https://abc.firebaseio.com/",
                    Host = "abc.firebaseio.com/"
                };
                IFirebaseClient client = new FirebaseClient(config);
    
                var obj = new Users
                {
                    FirstName = "test",
                    MiddleName = "user",
                    LastName = "xyz"
    
                };
    
                SetResponse response = client.SetAsync("Profile", "YourID");//you can use Set() as well
                response = client.SetAsync("Profile/YourID", obj);//you can use Set() as well
    
    0 讨论(0)
  • 2020-12-13 13:22

    if database reference child is fixed string, new value will not add. just it will update the previous value. for example :

    DatabaseReference myRef = FirebaseDatabase.getInstance().getReference(); String mText = // get data from editText or set your own custom data

    now if I insert data like this:

    myRef.child("abc").child("cba").setValue(mText);

    every time I insert data it will update my previous data. It will not add new data. Because my reference is fixed here(myRef.child("abc").child("cba") // this one, which is always fixed).

    Now change the the value of child "cba" to a random or dynamic value which will not fix. For example:

    Random rand = new Random(); // Obtain a number between [0 - 49]. int n = rand.nextInt(50); myRef.child("abc").child(String.valueOf(n)).setValue(mText);

    In this case it will add a new value instead of updating. because this time reference is not fixed here. it is dynamic. push() method exactly do the same thing. it generates random key to maintain unique reference.

    0 讨论(0)
  • 2020-12-13 13:22

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

    0 讨论(0)
提交回复
热议问题