是否可以检查集合或子集合是否存在?

Ahs*_*ath 12 javascript node.js firebase google-cloud-firestore

有没有办法检查firejs的firestore中是否存在子集合?

目前我doc.exists用于文档,但我需要检查文档中是否存在子列,以便写入一些数据.

Eli*_*hen 16

马特乌斯的答案对我没有帮助.可能它已经改变了.

.collection(..).get()返回一个具有该属性的QuerySnapshotsize,所以我刚刚做了:

admin.firestore.collection('users').doc('uid').collection('sub-collection').limit(1).get()
    .then(query => query.size);
Run Code Online (Sandbox Code Playgroud)

  • 这是。它会更快,并且对您的配额的影响会更少 (2认同)

Mat*_*lva 14

就在这里.您可以使用docs.length来了解子集合是否存在.

我做了一个样本来指导你,希望它有所帮助.

 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');
          }
        });
    }
  });
Run Code Online (Sandbox Code Playgroud)

  • 太好了,但是实际上不会读取N次。如果是这种情况,最好限制返回的docs => * .limit(1)的数量。 (5认同)
  • 如果集合不包含任何文档怎么办?并且仍然存在? (2认同)
  • @AkashGorai 没有。没有空集合。 (2认同)

Cho*_*ppy 6

更准确地说:

const querySnapshot = await admin.firestore().collection('users').doc('uid').collection('sub-collection').limit(1).get()
if (querySnapshot.empty) {console.log('sub-collection not existed')}
Run Code Online (Sandbox Code Playgroud)