我能够将文档保存到 firestore,但我也想将新保存的文档 ID 保存到同一个文档中,我正在尝试下面的示例,但效果不好
String id = db.collection("user_details").document().getId();
Map map = new HashMap<>();
map.put("username", username);
map.put("email", email);
map.put("id", id);
UserRef.document(id).set(map).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
//progressbar invisible;
;
}
});
最佳答案
每次调用 document()
时,您都会获得一个新的唯一 ID。因此,请确保只调用一次,这样您就只处理一个 ID。
首先获取文档引用:
DocumentReference ref = db.collection("user_details").document();
获取其ID:
String id = ref.getId();
然后编写要发送的数据:
Map map = new HashMap<>();
map.put("username", username);
map.put("email", email);
map.put("id", id);
最后,将该数据放入前面引用的文档中:
ref.set(map)...
关于java - 如何在android Firestore的文档字段中保存文档ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58457043/