在Firestore中一步添加呼叫时如何获取ID? [英] How to get the id when call add in one step in Firestore?
本文介绍了在Firestore中一步添加呼叫时如何获取ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道要获取ID:
String cityId = db.collection("cities").document().getId();
db.collection("cities").document(cityId).set(city);
但是更容易:
db.collection("cities").add(city);
但是如何获取ID? .add(city).getId()
无效.文档中没有信息.
But how to get id? It not work .add(city).getId()
. No information in docs.
推荐答案
在Firestore中一步添加呼叫时如何获取ID?
How to get the id when call add in one step in Firestore?
无法像使用 document()
调用时那样一步一步地获得文档ID.为了解决这个问题,您应该添加一个完整的侦听器.试试这个:
There is no way in which you can get the document id in a single step, as you do when using a document()
call. To solve this, you should add a complete listener. Try this:
db.collection("cities").add(city).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
@Override
public void onComplete(@NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
DocumentReference document = task.getResult();
if (document != null) {
String id = document.getId(); //Do what you need to do with the document id
Log.d(TAG, id);
}
}
}
});
这篇关于在Firestore中一步添加呼叫时如何获取ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文