簡體   English   中英

Cloud Firestore:向文檔添加字段值

[英]Cloud Firestore: Add Field Value To Document

我想創建一個名為question_count的字段值,我想增加該值並將其添加到我的雲 Firestore 文檔中。 我已經試過了:

document_reference.update("question_count", FieldValue.increment(1))

問題:我必須手動將question_count字段添加到我的雲 Firestore 文檔中,然后上面的代碼將增加該值。 Cloud Firestore 儀表板我想要什么:有人告訴我,如果尚未在雲 Firestore 中創建字段值,則使用帶有指定字段值的 DocumentReference update(...)將創建該字段值。 這是一個錯誤的假設嗎?

update方法僅在文檔已經存在時才有效。 如果要進行寫,要么創建文檔更新它時,它已經存在,使用docRef.set(..., SetOptions.merge())

所以在你的情況下,類似於:

// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("question_count", FieldValue.increment(1));

document_reference.set(data, SetOptions.merge());

另請參閱有關寫入數據的文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM