Zorgan
Zorgan

Reputation: 9123

How to remove multiple elements from a Firestore Array dynamically?

I want to remove multiple elements from my Firestore array:

var eliminatedThisRound = []

for (const player in players){
    if (players[player].eliminated === false && players[player].answer !== answer) {
        eliminatedThisRound.push(players[player].uid);
    }
}
var update = {
    roundFinished: true,
    nextRound: date.valueOf() + 12000,seconds
    players: updatedPlayers,
    remainingPlayers: admin.firestore.FieldValue.arrayRemove(eliminatedThisRound)
}
await t.update(gameRef, update);

The above returns this error:

transaction failure: Error: Element at index 0 is not a valid array element. Nested arrays are not supported. 

So it would be fine if I knew the values, as I could do something like this:

remainingPlayers: admin.firestore.FieldValue.arrayRemove("player1", "player2")

However I haven't found a way to make the parameter of arrayRemove() dynamic.

Any idea?

Upvotes: 2

Views: 980

Answers (2)

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

You need to use the Spread operator, as follows, in order to pass all elements of eliminatedThisRound as arguments to the arrayRemove() method.

var eliminatedThisRound = []

for (const player in players){
    if (players[player].eliminated === false && players[player].answer !== answer) {
        eliminatedThisRound.push(players[player].uid);
    }
}
var update = {

    // ...

    admin.firestore.FieldValue.arrayRemove(...eliminatedThisRound)
}

await t.update(gameRef, update);

Note that you should have at least one element in the Array, otherwise you will call arrayRemove() with 0 argument while it requires at least 1 argument. So you may check the array length before assigning the remainingPlayers property to the update Object.

Upvotes: 7

dshukertjr
dshukertjr

Reputation: 18612

You can pass a single value or an array of values from variables like this to arrayRemove():

var removingPlayersId = ['player1', 'player2'];
  admin
    .firestore()
    .doc('game/someID')
    .set(
      {
        remainingPlayers: admin.firestore.FieldValue.arrayRemove(
          removingPlayersId
        ),
      },
      { merge: true }
    );

Upvotes: 1

Related Questions