Chandra Sekhar
Chandra Sekhar

Reputation: 19502

updateChildren() removes the old data

My Firebase DB has structure like this:

user
-    userId
     -    pics
          -    "key1" - "url1"
          -    "key2" - "url2"

Now I want to add a new picture to the same user. So I am using updateChildren().

HashMap<String, String> paths = new HashMap<>();
paths.put("/user/<userId>/pics/key3", "url3");
dbRef.updateChildren(paths);

Since there is no "key3", so the expectation is it should add a new node with new value. But instead of adding, it deletes the old nodes too. So at the end of this execution, I have only one pic instead of 3.

I know we can solve this using transaction, but for that we need to download the whole data to client and re-upload it. Any alternative to do it without transaction?

Moreover, transactions are to avoid synchronous update of sme child, since I don't have any child "user-userId-pics-key3", it should not have any problem solving it without transaction.

Upvotes: 0

Views: 421

Answers (3)

Dulaj Atapattu
Dulaj Atapattu

Reputation: 446

Try this.

mDatabase.child("user").child(userId).child("pics").child("key3").setValue("url3");

Upvotes: 0

npk
npk

Reputation: 1800

updateChildren updates all the child nodes. Hence when there is no value, it is updated with null. You may use setValue() method here.

dbRef.child("/user/<userId>/pics/key3").setValue("url3");

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

I just ran this minimal code snippet based on yours:

DatabaseReference dbRef = database.getReference("46503277");
HashMap<String, Object> paths = new HashMap<>();
paths.put("pics/key3", "url3");
dbRef.updateChildren(paths);

And it added key3 to the existing key1 and key2 (see here). If that is not happening for you, something else must be going on.

Upvotes: 1

Related Questions