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