Is possible to check if a collection or sub collection exists?
Yes, there is. You can use docs.length to know if the subcollection exists.
I made a sample to guide you, hope it helps.
this.db.collection('users').doc('uid')
.get().limit(1).then(
doc => {
if (doc.exists) {
this.db.collection('users').doc('uid').collection('friendsSubcollection').get().
then(sub => {
if (sub.docs.length > 0) {
console.log('subcollection exists');
}
});
}
});
This is how I was able to check if a collection exists?
I target the document path first, then if it exists, It means the collection afterwards exists and I can access it.
> db.collection("collection_name").document("doc_name").get() > .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { > @Override > public void onComplete(@NonNull Task<DocumentSnapshot> task) { > if(task.isSuccessful()){ > DocumentSnapshot result = task.getResult(); > if(result.exists()){ > *//this means the document exist first, hence the > //collection afterwards the doc_name will > //exist...now I can access the collection* > db.collection("collection_name").document("doc_name").collection("collection_name2").get() > .addOnCompleteListener(task1 -> { if(task1.isSuccessful()){ > ... > } }); } } });
Mateus' Answer didn't help me. Probably it has been changed over the time.
.collection(..).get()
returns a QuerySnapshot which has the property size
, so I just did:
admin.firestore
.collection('users')
.doc('uid')
.collection('sub-collection')
.limit(1)
.get()
.then(query => query.size);
To be more precise:
const querySnapshot = await admin.firestore().collection('users').doc('uid').collection('sub-collection').limit(1).get()
if (querySnapshot.empty) {console.log('sub-collection not existed')}