简体   繁体   English

Firebase 创建文档并递增

[英]Firebase create a document and increment

I am trying to increment a value for my documents;我正在尝试增加我的文档的价值; Sometimes the document does not exist, so I need to create it and then update it.有时文档不存在,所以我需要创建它然后更新它。

    my_ref = db.collection(u'my_col').document(f"my_doc_key")
    my_doc = my_ref.get()

    if my_doc.exists:
        my_ref.update({"count": firestore.Increment(1)})
    else:
        my_ref.set({"count": 1})

I know I can use update() and Increment() if the document exists.我知道如果文档存在,我可以使用update()Increment() I know that if the document does not exist, I can create it and set a collection inside it with set() .我知道如果文档不存在,我可以创建它并使用set()在其中设置一个集合。 Is there a way I can do this in one method?有没有办法用一种方法做到这一点? Something like this:像这样:

    my_ref.set({"count": firestore.Increment(1)})

Solved it using merge=True parameter使用merge=True参数解决了它

     my_ref = db.collection(u'my_col').document(f"my_doc_key")
     my_ref.set({"count": firestore.Increment(1)}, merge=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Native Firebase 如何让文档 ID 自动递增 1 - React Native Firebase How To Have Auto Document Id Increment by 1 Firebase 云 Function 计划创建文档 - Firebase Cloud Function schedule to create document Firebase实时获取并自增 - Get and increment in Firebase Realtime Firebase function,增加一个值 - Firebase function, increment a value Firebase Firestore Increment FieldValue 不递增 - Firebase Firestore Increment FieldValue does not increment Firebase 9 - 在用户成功注册后尝试创建用户文档 - Firebase 9 - Trying to create a user document once a user successfully signs up 您是否需要创建一个单独的集合/文档来读取带有 firebase 云 function 的聚合文档 - do you need to create a separate collection/document for reading an aggregated document with firebase cloud function 获取自动生成的文档 ID 以创建文档或更新文档 Firestore / Firebase 中的数组的更好方法 - Better way to get document ID which was auto generated to create the doc or update an array inside the document Firestore / Firebase Firebase setDoc() 未创建文档 - Firebase setDoc() not creating document 如何从也有集合的 firebase 文档创建 Object? - How do I create an Object from a firebase document that also has a collection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM