简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM