简体   繁体   English

如果文档存在,则 Firestore 增量值,否则设置它

[英]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.

相关问题 mongodb增量(如果存在),否则插入 - mongodb increment if exists otherwise insert 使用 firestore.FieldValue.increment(1) 时如何解决错误“参数“dataOrField”的值不是有效的 Firestore 文档”? - How to resolve error "Value for argument "dataOrField" is not a valid Firestore document" while using firestore.FieldValue.increment(1)? 如果 object 属性值存在,如何增加它,否则设置初始值? - How to increment an object property value if it exists, else set the initial value? Firebase / Firestore:不存在文档,但应该 - Firebase / Firestore: No document exists but it should 如果值存在则应用过滤器,否则忽略-猫鼬 - Apply filter if value exists otherwise ignore - mongoose 关于 Firestore 文档的更新值 - On Update value of firestore document 检查 mongoose sava() data 如果不存在则创建文档,否则更新数据 - checked mongoose sava() data Create document if not exists, otherwise, update data 检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 - Check if document already exists and if yes then update, otherwise create new - Mongoose 如何检查firestore文档中是否存在字段? - How to check whether field exists or not in the firestore document? 检查 Firebase Firestore 中是否存在文档,如果不存在则新建一个 - Check if a document exists in Firebase Firestore, if not create a new
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM