首页 > 解决方案 > 在 Firebase Firestore 上查询文档时获取空查​​询

问题描述

我想构建一个 Firebase 函数来检查“朋友”集合中的“计划,==,真”,然后在“文件”集合中使用“fname”创建一个新文档。

我的 Firetore 设置如下:

 Users (collection)
    User IDs (documents)
         |
         |
  Friends (collection)
     Friends (documents with auto IDs)
     [fname, scheduled: true/false]
            |
            |
         Filings (collection)
            Filings (documents with auto IDs)  

这是一个屏幕截图:

每当我运行以下函数时,我都会收到一条错误消息,指出文档为空,即使它不是。我不明白为什么会这样。希望得到您的建议

exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun(async context => {
    const task = await (db.collection('friends').where('scheduled', '==', true).get());

    if (task.empty) {

        console.log('doc is empty');
        return;
    }

    task.forEach(element => {
        console.log(element.id, '==>' , element.data());
    
    });

  });

标签: node.jsfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


您的friends集合嵌套在users文档下。您的代码仅访问可能不存在db.collection('friends')的顶级集合。friends

要访问所有friends集合,请使用:

db.collectionGroup('friends').where('scheduled', '==', true).get()

推荐阅读