Reputation: 23
I tried to insert new data into a table in Firebase real-time database, but setValue()
and updateChildren()
both are overwritten previous table and value.
I know that setValue()
is replacing previous data, but in my case, updateChildren()
is also overwriting previous data.
In the Firebase console
, It seems like both methods are delete
the previous table and create a new table.
Firebase console
when updateChildren()
is executed
Is my code wrong?
My database structure is:
-accounts
- $userId
- missions
- $productId
- ...
and Code is:
val missionsReference = FirebaseDatabase.getInstance().getReference("accounts").child(userId).child("missions")
val mission = Mission(product.id, product.imageUrl, product.title, product.logoUrl, remain.timeInMillis, "", -1, snsAddress)
missionsReference.child(product.id).setValue(mission)
val missionValue: Map<String, Any> = mission.toMap()
val missionUpdate: HashMap<String, Any> = HashMap()
missionUpdate[product.id] = missionValue
missionsReference.updateChildren(missionUpdate)
/* I also tried following methods, but it overwrites too.
FirebaseDatabase.getInstance().getReference("accounts/$userId/missions/${product.id}").setValue(mission)
missionsReference.push().setValue(mission)
*/
Upvotes: 0
Views: 1970
Reputation: 23
OK, I gave up create missions array in account table. and I tried like, and it works. 😕
FirebaseDatabase.getInstance().reference.child("missions").child(id).setValue(mission)
Still I don't know why this method is works and previous methods are not works. In my opinion, it looks like problem of database level(or depth?)
Screenshot of Firebase console. it works 🤔
Upvotes: 0
Reputation: 138824
Seeing your database structure and assuming you have to achieve this:
Firebase-root
|
--- accounts
|
--- userId
|
--- missions
|
--- 0
| |
| --- //Mission details
|
--- 4
|
--- //Mission details
Please use the following lines of code:
val missionsReference = FirebaseDatabase.getInstance().reference.child("accounts").child(userId).child("missions")
val mission = Mission(product.id, product.imageUrl, product.title, product.logoUrl, remain.timeInMillis, "", -1, snsAddress)
missionsReference.child("4").setValue(mission)
But instead of passing a hardcoded value to the child()
function, I recommend you using the random key are generated by the push()
function like this:
missionsReference.push().setValue(mission)
Now, your database structure will look like this:
Firebase-root
|
--- accounts
|
--- userId
|
--- missions
|
--- randomId
| |
| --- //Mission details
|
--- randomId
|
--- //Mission details
Thre is no need to use updateChildren()
function in this case. This function is used to update properties under a Mission
object, for exmaple if you want to change the `imageUrl`` property.
Upvotes: 2