Add an item to a list in Firebase Database

前端 未结 4 2033
礼貌的吻别
礼貌的吻别 2021-01-01 16:14

I have the following Firebase database structure. uIds is a type of List. I am trying to add another uId under uIds with

4条回答
  •  佛祖请我去吃肉
    2021-01-01 16:58

    There is a good old article from the Firebase official blog explaining why we should avoid array in our database : Arrays are Evil

    So it's not possible to modify an array without replacing the array. I suggest to change your database structure to this

    "requests" : {
        "" : {
            "interests" : [ "x" ],
            "live" : true,
            "uIds" : {
                "" : "user1",
                "" : "user2"
            }
        },
        "" : {
            "interests" : [ "y" ],
            "live" : true,
            "uIds" : {
                "" : "user2"
            }
        }
    }
    

    To get the pushKey, you can use push() method (the same as what you have done to each Request item)

    Then the code will be like this if you just want to add a new uid to a request.

    String requestKey = "request001";
    mDatabase.child("requests").child(requestKey).child("uIds").push().setValue("user2");
    

    Comment here if you have questions, hope this helps :)

提交回复
热议问题