更新时间:2023-02-14 09:15:32
是的,使用 DocumentSnapshot
可以在不存储的情况下获取 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.
QueryDocumentSnapshot document = change.getDocument();
Client client = document.toObject(client.class).withId(document.getId());
// you can apply your actions...
}
}
});
documentSnapshot.getId())
将获取集合中 Document 的 id,而无需将 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