temporary_user_name
temporary_user_name

Reputation: 37098

How to reconcile array creation with array appending?

At one point in my code I'm creating a node in my realtime db like so:

const ref = await lobbyGamesRef.push({
  players: [{ uid: context.auth.uid }],
  // other properties omitted, but there's like 6 in all
});

It's an array of one because the host has just created a game and so is currently the only person in it.

When another player goes to join, I'm running this code:

await db.ref(`/lobbyGames/${data.gameKey}/players`).push({
  uid: context.auth.uid
});

The result, as someone familiar with realtime db might predict, is this: enter image description here

The array gets created initially with numeric indices, and then push creates an id for the next thing instead of continuing the indices.

I saw in this question that childByAutoId is recommended, but after reading the reference on it I honestly couldn't see how it would be used here.

Ideally I would like to have either all numeric or all uuid keys, idk. I just want consistency! And I'd rather not have to read the property just to write to it, that's not too efficient.

Upvotes: 0

Views: 38

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317760

If you want to use push at all, you have to use it consistently. You won't be able to pass an array to initially populate the child. For example, you probably want to do this:

const ref = await lobbyGamesRef.push().child("players").push({
  uid: context.auth.uid
});

Upvotes: 1

Neoflies
Neoflies

Reputation: 293

As the Firebase Realtime database specify, it will automatically generate a unique ID whenever you push a new item into the array enter image description here

In your situation, when you first initialize, your Ref is pointing to a specific game, later on, when you add a new player, your Ref is pointing to the players array of a specific game. I would suggest when you first added a game, just initialize your players with an empty array and call push() in a separated function

Upvotes: 0

Related Questions