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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53332471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:47:06  来源:igfitidea点击:

Checking if a document exists in a Firestore collection

javaandroidfirebasegoogle-cloud-firestore

提问by Emil Sharier

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?

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

Thanks :)

谢谢 :)

回答by HussainAbbas

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

回答by Rehman Murad Ali

Make the document structure like this one:

使文档结构像这样:

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

collectionName(Collection) -> documentId(Document) -> id = documentId(和其他字段)

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

回答by Alex Mamo

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

如果您想根据它检查特定文档是否存在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());
        }
    }
});

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:

如果您没有文档 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());
        }
    }
});

回答by Nadun Liyanage

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
                    }
                }

            });