简体   繁体   中英

Check for document existence in Firestore

I'm trying to find if some item exists in my database.

If it does not exist, I had like to add it.

If it exists, I had like to show a message.

The code im using:

CollectionReference colRefMyBooks = db.collection( "Users" ).document( auth.getUid() ).collection( "MyBooks" );
Query queryMyBooks = colRefMyBooks.whereEqualTo("BookID", bookId);
queryMyBooks.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                Toast.makeText(BookDetailActivity.this, "Book already in my list", Toast.LENGTH_SHORT).show();
            }
        } else {
            db.collection( "Users" ).document( auth.getUid() ).collection( "MyBooks" ).add( general_book );
        }
    }
});

This code works good as long as there is a collection "MyBooks" . However, if there is no collection "Mybooks" I want it to consider it as the task is not successful and therefore to add the item.

What I do get is that it skips the whole onComplete and therefore does not add anything.

Does it mean that I have to check first if a collection exists and inside of it if document?

Thank you

A query that finds no documents will always be considered "successful", regardless of whether or not any collections exist. This behavior can't be changed.

What you'll have to do instead is check if there are no documents in the result set and decide what you want to do from there:

queryMyBooks.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            QuerySnapshot snapshot = task.getResult();
            if (snapshot.isEmpty()) {
                db.collection( "Users" ).document( auth.getUid() ).collection( "MyBooks" ).add( general_book );
            }
            else {
                for (QueryDocumentSnapshot document : snapshot) {
                    Toast.makeText(BookDetailActivity.this, "Book already in my list", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
});

Note that collections don't really "exist". There are no operations to add or delete collections. There are just operations to modify documents. A collection only appears in the console if it contains at least one document. If it contains no documents, it just disappears.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM