如何使用kotlin数据类获取Firestore文档的文档ID

我有kotlin数据类

data class Client( val name: String = "", val email: String = "", val phone: String ="") { constructor():this("","","")} 

我已经有Firestore将数据填充到类中,但是我不知道如何将文档ID导入到数据类中,而不必将其设置在文档中。 这可能吗?

是的,可以使用DocumentSnapshot来获取id而不存储它。 我会尝试在这里建立完整的例子。

我创建了一个通用的Model类来保存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; } } 

然后你用任何模型扩展它,不需要实现任何东西:

 public class Client extends Model 

如果我有这里的客户列表,试图查询列表只获取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:

 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())将获取集合中Document的id,而不会将id保存到文档中。

使用模型不会让你编辑任何你的模型,不要忘记使用@IgnoreExtraProperties

这是我如何解决这个问题。

 data class Client( val name: String = "", val email: String = "", val phone: String ="", @get:Exclude var id: String = "") { constructor():this("","","") } 

我使用@get:排除在id上以确保id在保存时不会被发送到Firestore,然后在获取客户端列表时执行以下操作:

 snapshot.documents.mapTo(list) { var obj = it.toObject(Client::class.java) obj.id = it.id obj } 

将新对象的标识设置为文档引用的标识。