Tom
Tom

Reputation: 1565

Firestore increment value if document exists, otherwise set it

I'm looking to do an upsert with a firestore document like:

gameDb
        .collection("player-scores")
        .doc(playerId)
        .update({ score: firebase.firestore.FieldValue.increment(1) });

If playerId document exists, then update the score, otherwise set it to 1.

If I do

gameDb
        .collection("player-scores")
        .doc(playerId)
        .set({ score: firebase.firestore.FieldValue.increment(1) });

it works as I want for a moment and score is set to either 1 or the incremented value, but then the incremented score is overwritten by 1

Upvotes: 5

Views: 1760

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83163

By using the {merge: true} option of the set() method it will do the trick:

gameDb
        .collection("player-scores")
        .doc(playerId)
        .set({ score: firebase.firestore.FieldValue.increment(1) }, {merge: true});

If the document does not exist, the field is initialized to 1, if it exists, it is incremented.

Upvotes: 19

Related Questions