Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to check if a collection or sub collection exists?

Is there a way to check if a sub collection exists in firestore for nodejs?

Currently I am using doc.exists for documents but I need to check if a subcolletion exists within a document in order to write some data or not.

like image 589
Ahsath Avatar asked Dec 27 '17 19:12

Ahsath


2 Answers

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);
like image 103
Eliya Cohen Avatar answered Oct 06 '22 08:10

Eliya Cohen


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');
          }
        });
    }
  });
like image 24
Mateus Forgiarini da Silva Avatar answered Oct 06 '22 06:10

Mateus Forgiarini da Silva