Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 439
Zorgan Avatar asked Mar 25 '26 21:03

Zorgan


1 Answers

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.

like image 92
Renaud Tarnec Avatar answered Mar 28 '26 13:03

Renaud Tarnec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!