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

前端 未结 3 2021
我寻月下人不归
我寻月下人不归 2020-11-27 21:35

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 subco

相关标签:
3条回答
  • 2020-11-27 22:05

    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);
    
    0 讨论(0)
  • 2020-11-27 22:18

    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().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');
              }
            });
        }
      });
    
    0 讨论(0)
  • To be more precise:

    const querySnapshot = admin.firestore().collection('users').doc('uid').collection('sub-collection').limit(1).get()
    if (querySnapshot.empty) {console.log('sub-collection not existed')}
    
    0 讨论(0)
提交回复
热议问题