我需要在我的文档中添加一个项目到列表中。不幸的是,我的代码总是覆盖旧值。如何更改代码以始终添加新项?
db = FirebaseFirestore.getInstance();
String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
db.collection("Users").document(userid);
Map<String, Object> docData = new HashMap<>();
Map<String, Object> nestedData = new HashMap<>();
nestedData.put("Ernährung2", true);
docData.put("channelAbos", nestedData);
db.collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.set(docData);
发布于 2019-01-04 03:46:10
对于official documentation所说的SetOptions merge()
方法:
将set()调用的行为更改为仅替换其data参数中指定的值。set()调用中省略的字段将保持不变。
所以SetOptions.merge()
方法只会替换fieldPaths下的字段。任何未在fieldPaths中指定的字段都将被忽略,并且保持不变。
因此,如果文档不存在,则会创建该文档。如果文档确实存在,除非您指定将数据合并到现有文档中,否则它的内容将与新提供的数据合并( will be overwritten
)。因此,为了解决这个问题,请更改以下代码行:
db.collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.set(docData);
至
db.collection("Users").document(FirebaseAuth.getInstance().getCurrentUser().getUid())
.set(docData, SetOptions.merge());
发布于 2019-01-04 03:44:31
According to the documentation,每次用一个参数调用set()都会覆盖整个文档。
如果文档不存在,则将创建该文档。如果文档确实存在,则其内容将被新提供的数据覆盖
如果要向现有列表中添加值,则应使用same page of documentation中所述的FieldValue.arrayUnion()
如果文档包含数组字段,则可以使用arrayUnion()和arrayRemove()添加和删除元素。arrayUnion()将元素添加到数组中,但只添加尚不存在的元素。
https://stackoverflow.com/questions/54028764
复制相似问题