how to check firebase firestore user data collection is empty - android

I'm making a note app and I have a problem. It is how to check if Firebase Firestore user data collection is empty.
Query query = firebaseFirestore.collection("mNotes").document(firebaseUser.getUid()).collection("userNotes").orderBy("title", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<firebasemodel> allusernotes = new FirestoreRecyclerOptions.Builder<firebasemodel>().setQuery(query, firebasemodel.class).build(); ```
this code is used to get data from Firestore.
how can I check user data collection is empty with the if statement.
I am a beginner.

How to check Firebase Firestore user data collection is empty?
Firestore doesn't have the concept of an empty collection. If a collection doesn't contain any documents, it doesn't exist at all. So there is no API that can help you check if a collection actually exists. A collection in Firestore will start to exist if there is at least one document present in it.
So to solve this, you might consider checking the number of documents within the collection or subcollection like this:
val db = Firebase.firestore
val usersRef = db.collection("users")
usersRef.get().addOnCompleteListener {
if (it.isSuccessful) {
val numberOfDocs = it.result.documents.size
if (numberOfDocs > 0) {
Log.d(TAG,"users collection already exists!")
}
}
}

Related

Filter and get all sub-collections by using where clause in Firestore

In firestore I have some sub-collections inside each collection just like below:
Collection1 -> id -> Sub-collection -> scId -> Data
So here I want to get all data from sub-collections by the help of the where clause. I tried one query like the below which is failing.
db.collection("Collection1").whereEqualTo("eDate", selectedDate)
.get().addOnSuccessListener(queryDocumentSnapshots -> {
List<Exp> mData = queryDocumentSnapshots.toObjects(Exp.class);
Here eDate is coming under the Data which is inside each sub-collection.
So is there any way to do that or any suggestions on how to do that or about the mistakes which I did here?
Firestore queries are shallow and do not extend above or below the named collection being queried. The query you show here will only return documents immediately within "Collection1". It will not consider any documents in nested subcollections.
If you want documents in a subcollection, you will have to build a CollectionReference to that subcollection, and query it individually. You can't query all subcollection nested under a document at the same time. You can't query across differently-named subcollections at the same time.
If this behavior does not meet the needs of your app, you should consider restructuring your data to do so, or building your app to perform as many queries as needed to get all the documents from among all the collections where they live.

Get db from current user firestore query kotlin android

whats up?
I have an app that displays a list of items on Firestore using Kotlin and RecyclerView (from FirebaseUI api).
The DB is structured like this:
Users/userID/document_month_year
I need to query the data from the current user.
Each user has his own document_month_year document.
I read a lot of posts here, but each one tell one thing.. thereĀ“s no consense and nothing seems to work.
This query just sends me all documents from all users, how can I fix this?
private val queryFilteredByPaidStatus = db.collectionGroup(collectionName).whereEqualTo("users", userId)
Like this is an important question, here is the awnser that I
private val queryTest = db.document("users/"+userId).collection(collectionName)
fun getData() : FirestoreRecyclerOptions<Expense> {
return FirestoreRecyclerOptions
.Builder<Expense>()
.setQuery(queryTest, Expense::class.java)
.build()
}
Create a separate collection for documents to be read i.e month_year and for each document, add a field inside it which tells you the uid of the authenticated user, to which the document belongs to. Now you can query the collection like:
firestoreDB.collections("month_year").whereEqualTo("uid",auth.currentUser.uid)

Firestore: Check if virtual document exists

I am developing an android app, where users can register. To save user data, I user Firebase Firestore. So, When a user registers, a document with the FirebaseUser.userId as id get created.
val exampleObject = ExampleObject(exampleData1, exampleData2)
val firestoreUser = FirebaseAuth.getInstance().currentUser
firebaseFirestore
.collection("users")
.document(firestoreUser.uid)
.collection("exampleCollection")
.document("exampleDocument")
.set(exampleObject)
The document that gets created for each user only contains collections, therefore, Firestore does only create a "dummy document". So, how can I check if this document exists or not?
firebaseFirestore
.collection("users")
.document(firestoreUser.uid)
.get()
.addOnSuccessListener { doc->
if(doc.exists()) {
} else {
}
}
This does not work, because it is only a "dummy document", that does not really exist
Firestore does only create a "dummy document".
It does not create any document. That document does not exist because you didn't create it at all. What you did do, was only to create a subcollection under a document that never existed. In other words, you just reserved an id for a document in a collection and then you created a subcollection under it.
One thing to remember, in Cloud Firestore documents and subcollections don't work like filesystem files and directories. If you create a subcollection under a document, it does not implicitly create any parent documents. Subcollections are not tied in any way to a parent document.
So note that there is no physical document at that location but there is other data under the location, which is the exampleCollection subcollection. Remember that the "dummy document" that you are talking about becomes a real document only when you write at least a property that can hold a value in it.
So in your case, the following statement:
if(doc.exists())
Will be always evaluated to false.

Delete all subcollections of a particular document(i,e.currentuser doc) in collection when app is killed in kotlin/android [duplicate]

I have a collection called lists and it has documents who is ID represents the list ID. This document has a collection called employees and another one called locations.
The structure looks like this:
(lists)
-listId
(employees)
(locations)
If the user wants to delete a specific list then the problem is that we can't delete listId because that will keep the collection (as was mentioned by Firestore docs).
How can the structure be modeled to fit the needs? I can't seem to get around the need for subcollection.
Any recommendation?
There is no need to restructure your database in order to delete some collections. To delete an entire collection or subcollection in Cloud Firestore, retrieve all the documents within the collection or subcollection and delete them. So in order to delete a specific list, please use the following steps:
Find all documents beneath employees collection and delete them
Find all documents beneath locations collection and delete them
Delete the listId document
If you have larger collections, you may want to delete the documents in smaller batches to avoid out-of-memory errors. Repeat the process until you've deleted the entire collection or subcollection.
Even if the delete operation is not recomended by Firebase team because it has negative security and performance implications, you can still do it but only for small collections. If you need to delete entire collections for web, do so only from a trusted server environment.
For Android, you can use the following code:
private void deleteCollection(final CollectionReference collection, Executor executor) {
Tasks.call(executor, () -> {
int batchSize = 10;
Query query = collection.orderBy(FieldPath.documentId()).limit(batchSize);
List<DocumentSnapshot> deleted = deleteQueryBatch(query);
while (deleted.size() >= batchSize) {
DocumentSnapshot last = deleted.get(deleted.size() - 1);
query = collection.orderBy(FieldPath.documentId()).startAfter(last.getId()).limit(batchSize);
deleted = deleteQueryBatch(query);
}
return null;
});
}
#WorkerThread
private List<DocumentSnapshot> deleteQueryBatch(final Query query) throws Exception {
QuerySnapshot querySnapshot = Tasks.await(query.get());
WriteBatch batch = query.getFirestore().batch();
for (DocumentSnapshot snapshot : querySnapshot) {
batch.delete(snapshot.getReference());
}
Tasks.await(batch.commit());
return querySnapshot.getDocuments();
}

How to use Query in Firebase Firestore

I am using Firebase function and Firebase Firestore to develope an API which will store users data.
I wanted to locate the documents using the properties stored in their field. This is the Firebase document which states how to achieve the same.
// Create a reference to the cities collection
var citiesRef = db.collection('cities');
// Create a query against the collection
var queryRef = citiesRef.where('state', '==', 'CA');
I wanted to handle two situations
Where there is no document with the present conditions
Where there are more than two documents with the present conditions
How could the above two situation be handled?
Following our "discussion" in the comments above, in a Cloud Function you could do as follows, using the QuerySnapshot returned by the get() method:
admin.firestore().collection("cities")
.where('state', '==', 'CA')
.get()
.then(querySnapshot => {
if (querySnapshot.size == 0) {
console.log("0 documents");
} else if (querySnapshot.size > 2) {
console.log("More than 2 documents");
}
});
As said, above, just be aware that this will cost a read for each document in the collection. In case you have a very large collection, you could write a Cloud Function that update a counter each time a doc is added/removed to/from the collection.
The accepted answer does not show how to extract the data from each document and imo is only half the answer. the following will get you iterating through every document and extracting the data.
db.collection("cities").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});

Categories

Resources