繁体   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