[英]Firestore increment value if document exists, otherwise set it
I'm looking to do an upsert with a firestore document like:我正在寻找一个带有 Firestore 文档的 upsert,例如:
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.如果playerId
文档存在,则更新分数,否则将其设置为 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
它按我的意愿工作了一会儿,分数设置为1
或增加的值,但随后增加的分数被1
覆盖
By using the {merge: true}
option of the set()
method it will do the trick:通过使用set()
方法的{merge: true}
选项,它可以解决问题:
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.如果文档不存在,则该字段初始化为 1,如果存在,则递增。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.