我想检查我的集合“users”中是否存在文档,因为当我尝试此代码时,当文档不存在时(当没有文档在“user_uid”字段中具有正确的值):
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("users").whereEqualTo("user_uid", user.getUid())
.limit(1).get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
当我的文档符合我的条件 whereEqualTo("user_uid", user.getUid())
时,它就可以工作。
那么,如何检查是否存在字段 "user_uid"== user.getUid()
的文档?
最佳答案
我复制了您的代码,并尝试使用 limit(1)
实现 OnCompleteListener
。它在有结果和没有结果的两种情况下都对我有用。
Firestore
有一种方法可以通过检查是否 isEmpty()
来检查是否没有结果。或不,在执行任何操作之前。因为在迭代 getDocuments()
时执行任何操作大多数时候都会导致 IndexOutOfBoundsException
。
例如:
if (task.isSuccessful()) {
boolean isEmpty = task.getResult().isEmpty();
}
希望这对您有帮助。
关于android - 检查文档是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46993039/