Clark
Clark

Reputation: 2678

How do I update an Object Map inside a Firebase Object?

Newbie here!

So I am using Firebase. I basically have this condensed structure. I got to this structure by trying to follow what I have read (No arrays, etc).

I have an User Object which needs to contain a list of stuff. So I have ended up with this kind of thing in the database.

{
   name: "clark"
   friends: {
       billyTheKid: true,
       butcherOfBakersfield: true
   }
}

When I add a friend, I am doing this (again forgive the poor names)

this.$firebaseUserObserver.update({
  friends: {
    [friendID]: true
  }
});

When I do this, and I return to my example, then BillyTheKid is deleted and replaced by ButcherOfBakersfield.

I feel like I am getting set behavior despite using update so I must be handling the structure incorrectly.

Would anyone be able to offer me guidance?

Upvotes: 3

Views: 4420

Answers (2)

arneson
arneson

Reputation: 141

What happens if you go down one level before doing .update? Ex.

$firebaseUserObserver.$ref.child("friends").update({ [friendId]: true})

I think the update statement basically replaces each child of the node, instead of replacing the entire node which is what .set does. Basically it does a set on each child. Because of this it only works one level down in the structure.

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598708

Calling update() on a ref, iterates over the properties of the object you pass in and then calls set() for each of those. So you're indeed replacing the friends with each call.

The proper solution is to call update() on the right level in the tree:

this.$firebaseUserObserver.child('friends').update({
    [friendID]: true
});

But in this case that is not even needed, you can set call set() for the specific friend:

this.$firebaseUserObserver.child('friends').child(friendId).set(true);

Upvotes: 3

Related Questions