0

If I have firebase data something like this:

teams:{
    thunder: {
        wins: 3,
        losses: 2,
        draw: 1
    },
    warrior: {
        wins: 2,
        losses: 4
    }
}

How would I change the "warrior" key to "Warriors"? The only way I can think of is to load the "warrior" data, save it with the new key and then delete the old data. It feels a bit like a hack to me though, is there a better way to do it?

Marty.H
  • 1,194
  • 4
  • 16
  • 29

2 Answers2

1

Use an array instead and push teams to this array. Then have your structure like this:

teams: [
  {
    name: "thunder",
    wins: 3,
    draws: 2,
    loss: 1
  }
]

Then you can just update the name key directly without having to download the data first in order to update it.

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
1

The create a new node and blow out the old one is correct. But going forward a different structure will avoid the issue entirely.

Bottom line with any kind of database programming (for us): never tie keys directly to data. Always use some kind of 'random' or other key structure to reference your data.

Firebase provides a perfect tool for this in childByAutoId, which creates a 'random' child node name key.

Chrillewoodz answer is the answer... and to add some additional clarity

teams
  randomKey_0:
    team_name: "thunder"
    wins: 3
    draws: 2
    loss: 1
 randomKey_1:
    team_name: "warrior"
    wins: 3
    draws: 2
    loss: 1
 randomKey_2:
    team_name: "super dudettes"
    wins: 100
    draws: 0
    loss: 0

The randomKey_x is a firebase generated childByAutoId node name.

With this structure, you can change the team name, wins etc on the fly without altering the structure. And because you now have a reference, you can use it in other nodes to reference back to that team. For example, you could have a separate node to keep info about team members

team_members:
  randomMemberKey_0
     team_member_name: "Scott"
     height: "7.5"
     belongs_to_team: "randomKey_0"
  randomMemberKey_1
     team_member_name: "Billy"
     height: "6.5"
     belongs_to_team: "randomKey_0"
  randomMemberKey_2
     team_member_name: "Frank"
     height: "5.0"
     belongs_to_team: "randomKey_1"

With this structure you can query for information about the team itself or another query to search for any team member or members or information about them.

Jay
  • 34,438
  • 18
  • 52
  • 81
  • Thanks, in hindsight I should have done that. But probably not worth changing it now, as the only time it matters is if someone wants to change the name, which will not be a common thing. And on the plus side I have an easier to read data tree. – Marty.H Jul 08 '15 at 16:43