Nick Pampoukidis
Nick Pampoukidis

Reputation: 742

Write single value on firebase database without deleting the existing ones

I'am trying to add a single value my database without deleting the existing ones because I need them all. The structure is something like that /user/fav_post/{post_id_1,post_id_2,...}. The "fav_post" initially is empty and as the time goes by the user adds more fav_posts.

One way that solves this problem is downloading all favorite posts, putting them in a HashMap, add the new post and the push them to the database but this does not seem very optimal.

So what I am trying to achieve is to have all the favorite posts and to display them to the user.

 mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .setValue(postID); 

Edit: The end result should be like

Ther end result I want to be like that root

-User

--FavPosts

---postID1(String)

And when the user favorites another post the result should be like that:

root
-User

--FavPosts

---postID1(String)

---postID2(String)

Upvotes: 1

Views: 2055

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

What you're looking for is a set: an unordered collection of unique values. In the Firebase Database you'd store the post Id as a key and (since Firebase doesn't allow you to store a key without a value) true as the value.

So:

root: {
  User: {
    FavPosts: {
      postID1: true,
      postID2: true
    }
  }
}

You'd set these values with:

 mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .child(postID) 
       .setValue(true);

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317372

setValue() will overwrite the entire contents of the location. If you want to just add or update child values, use updateChildren() instead.

Upvotes: 2

Related Questions