检查 Firestore 集合中是否存在文档

我有一个 Firestore 集合树,我计划在其中只存储一个文档。我想检查该集合是否包含该文档,如果是,请检索该文档的ID!任何想法/想法?

谢谢:)


答案 1

如果要根据特定文档检查其是否存在,请使用以下代码行:document id

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference docIdRef = rootRef.collection("yourCollection").document(docId);
docIdRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Log.d(TAG, "Document exists!");
            } else {
                Log.d(TAG, "Document does not exist!");
            }
        } else {
            Log.d(TAG, "Failed with: ", task.getException());
        }
    }
});

如果您没有文档 ID,则需要使用查询并根据特定属性的值查找该文档,如下所示:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference yourCollRef = rootRef.collection("yourCollection");
Query query = yourCollRef.whereEqualTo("yourPropery", "yourValue");
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                Log.d(TAG, document.getId() + " => " + document.getData());
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

答案 2

试试这个。

FirebaseFirestore firestore = FirebaseFirestore.getInstance();
firestore.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()) {
                            boolean isEmpty = task.getResult().isEmpty();
                          }
                        }
                    });

推荐