Checking if a document exists in a Firestore colle

2020-08-13 06:07发布

问题:

I have a Firestore collection tree in which I plan to store only one document. I want to check if that collection contains that document and if so, retrieve the id of the document! Any ideas/thoughts?

Thanks :)

回答1:

If you want to check a particular document for existence based on its document id, please use the following lines of code:

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());
        }
    }
});

If you don't have the document id, you need to use a query and find that document according to a value of a specific property like this:

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:

Try this one.

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();
                          }
                        }
                    });


回答3:

Make the document structure like this one:

collectionName(Collection) -> documentId(Document) -> id = documentId(and other fields)

Now make a query:

FirebaseFirestore firestoreDatabase= FirebaseFirestore.getInstance();
firestoreDatabase.collection(COLLECTION_NAME)
            .whereEqualTo(DOCUMENT_ID, documentId)
            .get()
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    if (task.getResult().getDocuments().size() > 0)
                        // Here is your document with id
                }
            });


回答4:

DocumentReference docRef = db.collection("items").document("your_id");
            docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(DocumentSnapshot snap, FirestoreException fe) {
                    if (snap.exists()) {
                        //update
                    } else {
                        //Insert
                    }
                }

            });