如何使用Kotlin数据类获取Firestore文档的文档ID [英] How do I get the document ID for a Firestore document using kotlin data classes
问题描述
我有kotlin数据类
I have kotlin data class
data class Client(
val name: String = "",
val email: String = "",
val phone: String ="") {
constructor():this("","","")}
我已经用firestore将数据很好地填充到了类中,但是试图弄清楚如何将文档ID放入数据类而不必在文档本身中进行设置,我感到很困惑.这可能吗?
I have firestore populate the data into the class just fine, however I am at a loss trying to figure out how to get the document id into the data class without having to set it in the document itself. Is this possible?
推荐答案
是的,可以使用DocumentSnapshot
而不存储ID来获取ID.我将尝试在此处构建完整的示例.
Yes, it's possible to get id without storing it, using DocumentSnapshot
. I will try to build complete examples here.
我创建了一个通用的Model类来保存ID:
I created a general Model class to hold the id:
@IgnoreExtraProperties
public class Model {
@Exclude
public String id;
public <T extends Model> T withId(@NonNull final String id) {
this.id = id;
return (T) this;
}
}
然后,您可以使用任何模型对其进行扩展,而无需执行任何操作:
Then you extend it with any model, no need to implement anything:
public class Client extends Model
如果我在这里有客户端列表,请尝试查询列表以仅获取具有age == 20
的客户端:
If I have list of clients here, trying to query the list to get only clients with age == 20
:
clients.whereEqualTo("age", 20)
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot documentSnapshot : task.getResult().getDocuments()) {
// here you can get the id.
Client client = document.toObject(client.class).withId(document.getId());
// you can apply your actions...
}
} else {
}
}
});
如果使用的是EventListener
,则还可以获取如下所示的ID:
And if you are using EventListener
, you can also get the id like the following:
clients.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
// here you can get the id.
Client client = document.toObject(client.class).withId(document.getId());
// you can apply your actions...
}
}
});
documentSnapshot.getId())
会在不将ID保存到文档中的情况下为您获取集合中Document的ID.
documentSnapshot.getId())
will get you the id of the Document in the collection without saving the id into the document.
使用模型将不允许您编辑任何模型,也不要忘记使用@IgnoreExtraProperties
Using Model will not let you edit any of your models, and don't forget using @IgnoreExtraProperties
这篇关于如何使用Kotlin数据类获取Firestore文档的文档ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!